本文介绍了从ngrx/store效果返回forkJoin的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ngrx存储返回效果中forkJoin的结果,如以下伪代码所示:

I am trying to return the result of a forkJoin in my effect using ngrx store, like this pseudocode demonstrates:

@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或类似的内容.有任何想法吗?

How can I synchronously return an action from the result of a forkJoin like this? At the moment, I'm dispatching an action directly to the store within the forkJoin block, but this is rather smelly and I would like to know how I can return this action within the forkJoin block, using another operator such as map or something along those lines. Any ideas?

推荐答案

您不能从map()回调中返回一个Observable.您需要使用switchMap()(或另一个xxxMap())来执行此操作.您也不能订阅forkJoin可观察的.相反,您必须map():

You can't return an Observable from the map() callback. You need to use switchMap()(or another xxxMap()) to do that. You also can't subscribe to the forkJoin observable. Instead, you must 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))
        }
    })
)

这篇关于从ngrx/store效果返回forkJoin的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:11