Rxjs和ngrx-在效果中,成功/失败的正确结构是什么? [英] rxJS and ngrx - what is the right structure of success / fail inside an effect?

查看:18
本文介绍了Rxjs和ngrx-在效果中,成功/失败的正确结构是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在角度2项目中工作,使用ngrx和rxjs技术。

现在我有一个问题:

我试着声明一个效果。 该效果为http请求,仅当其成功时我才想调用其他http-请求,因此仅当它也成功时-然后调度一个成功操作。

我已通过引发错误对其进行了测试,但它始终会调度操作!

请参阅:

       @Effect()
createEntity$ = this.actions$.ofType(CREATE_ENTITY)
    .switchMap((action: CreateEntity) => {

        return this.httpService.getDefaultEntityData(action.payload.type).map((entity) => {
            return  Observable.throw("testing only");
            /*if (entity) {
                 entity.title = entity.type;
                 return this.httpService.addEntity(entity);
            }*/
        })

            .catch((error) => Observable.of(new createEntityFailure(error)))
            .map(mappedResponse => ({ type: CREATE_ENTITY_SUCCESS, payload: mappedResponse }))
    });

推荐答案

这样如何:

this.actions$
    .ofType(CREATE_ENTITY)
    .map((action: CreateEntity) => action.payload)
    .switchMap(payload =>
      this.httpService.getDefaultEntityData(payload.type)
        .mergeMap(entity => this.httpService.addEntity(entity))
        // .mergeMap(entity => Observable.throw('error')) // or this for testing
        .mergeMap(response => new actions.Action(...))
        .catch(error => new actions.Error(...))
    );

这篇关于Rxjs和ngrx-在效果中,成功/失败的正确结构是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆