从ngrx / store效果返回forkJoin的结果

时间:2018-04-11 15:53:06

标签: angular rxjs ngrx ngrx-effects

我试图使用ngrx商店在我的效果中返回forkJoin的结果,就像这个伪代码所示:

@Effect()
someEffect$: Observable<Action> = this.action$.pipe(
    ofType<SomeActionType>(ActionTypes.SomeActionType),
    switchMap((action: any) => 
        this.http.get<any>('some/url').pipe(
            map(someResult => {
                // this implementation is unimportant, just the gist of the flow I'm after
                const potentialResults = oneOrMany(someResult);

                if( potentialResults.length === 1 )   {
                    return new SomeAction(potentialResults[0]);
                } else {
                    observables: Observable<any> = getObservables(someResult);

                    forkJoin(observables).subscribe((result) =>
                        // this is where I get stuck    
                        return new SomeAction(result);
                    )
                }
            }
        ))
)

如何从forkJoin这样的结果中同步返回某个操作?目前,我已将行动直接发送到forkJoin区块内的商店,但这很臭,我想知道如何在forkJoin区块内返回此​​操作,使用其他运算符,如map或其他类似的行。有任何想法吗?

2 个答案:

答案 0 :(得分:1)

您无法从map()回调中返回Observable。您需要使用switchMap()(或其他xxxMap())来执行此操作。您也无法订阅forkJoin observable。相反,您必须map()

someEffect$: Observable<Action> = this.action$.pipe(
    ofType<SomeActionType>(ActionTypes.SomeActionType),
    switchMap(() => this.http.get<any>('some/url'),
    switchMap(someResult => {
        const potentialResults = oneOrMany(someResult);
        if (potentialResults.length === 1)   {
            return of(new SomeAction(potentialResults[0]));
        } else {
            const observables: Array<Observable<any>> = getObservables(someResult);
            return forkJoin(observables).map(result => new SomeAction(result))
        }
    })
)

答案 1 :(得分:0)

您可以创建主题并返回它:

someEffect$ = createEffect(() => this.actions$.pipe(
ofType(SomeType.Save),
mergeMap(action => {
  const obsList: Observable<any>[] = createList();

  const sub: Subject<Action> = new Subject<Action>();
  forkJoin(obsList).subscribe(() => {
    sub.next(new SomeAction());
    sub.complete();
  });
  return sub;
})));