从NGRX /存储效应返回forkJoin的结果(Returning the result of a

2019-10-28 14:07发布

我试图返回的结果forkJoin在我的使用效果店NGRX,这样的伪代码演示:

@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沿着什么这些行。 有任何想法吗?

Answer 1:

你不能从地图()回调返回可观察到的。 您需要使用switchMap()或其他xxxMap()来做到这一点。 你也不能订阅forkJoin观察到。 相反,你必须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))
        }
    })
)


Answer 2:

您可以创建一个主题,并将其返回:

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;
})));


文章来源: Returning the result of a forkJoin from an ngrx/store effect