繁体   English   中英

根据效果验证,取消ngrx效果服务调用的更好方法是什么?

[英]What is the better way to cancel a ngrx effect service call, based on a validation in the effect?

我有这个ngrx效果,在此示例中正在调用电影服务,但取决于值选择器,如果此值符合验证中的预期,则该效果会发送新操作,因此我避免调用该服务,因为条件。 现在,由于此错误,我无法在if块中使用其他操作(这将更具描述性):

类型“可观察”不能分配给类型“可观察| ((... args:any [])=>可观察)'。

类型“可观察”不能分配给类型“可观察” .ts(2322)。

有什么更好的方法来处理这种情况?

loadMovies$ = createEffect(() => this.actions$.pipe(
        ofType('[Movies Page] Load Movies'),
        concatMap(action => of(action).pipe(withLatestFrom(this.store.select(getBlockBuster)))),
        mergeMap(([{payload}, foundBlockBuster]) => {
            if (!foundBlockBuster) {
                // in order to avoid errors we need to use this({ type: '[Movies API] Movies Loaded Success', payload: movies }))
                return of({ type: '[Movies] The block busters are rent' })
            }
            return this.moviesService.getAll()
                .pipe(
                    map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
                    catchError(() => of({ type: '[Movies API] Movies Loaded Error' }))
                )
            })
        )
    );

发生此错误的原因是,您应该返回Observable<action>而您的代码将返回两种类型的对象常量(假定为Action类型),一种仅具有type属性,而另一种具有typepayload 要解决此错误,请使用Action数组,然后将对象文字推入该数组,然后返回该数组,如下所示:

loadMovies$ = createEffect(() => this.actions$.pipe(
        ofType('[Movies Page] Load Movies'),
        concatMap(action => of(action).pipe(withLatestFrom(this.store.select(getBlockBuster)))),
        mergeMap(([{payload}, foundBlockBuster]) => {

            const actions = new Array<Action>();

            if (!foundBlockBuster) {
                actions.push({ type: '[Movies] The block busters are rent' });
                return actions;                
            }
            return this.moviesService.getAll()
                .pipe(
                    mergeMap(movies => {
                      actions.push({ type: '[Movies API] Movies Loaded Success', payload: movies });
                      return actions;
                    }),
                    catchError(() => {
                      actions.push({ type: '[Movies API] Movies Loaded Error' });
                      return actions;
                    })
                )
            })
        )
    );

另外,您可以像这样将对象文字类型转换为<Action>

<Action>{ type: '[Movies] The block busters are rent' }

但是我更喜欢使用数组,因为如果我的应用程序逻辑需要的话,数组允许调度多个动作。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM