RxJS / Angular 2 / @ ngrx / store /影响如何组合动作

时间:2016-08-21 23:30:09

标签: angular rxjs

我使用Angular2和@ ngrx / store&效果......我有这样的身份验证效果

@Effect() authenticate$ = this.updates$
  .whenAction(AuthActions.AUTHENTICATE_REQUEST)
  .switchMap(update => this.api.post('/authenticate', update.action.payload)
  // somehow use data in the original `update` to work out if we need to
  // store the users credentials after successful api auth call
    .map((res:any) => this.authActions.authenticateSuccess(res.json()))
    .catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
)

update.action.payload对象中的rememberMe标志。所以...如果设置为true我需要将凭据存储在LocalStorage服务 AFTER 中,api请求已成功返回...但显然不是,如果有错误。

如何在switchMap运算符内部实现这一点,我们只能访问api post调用的结果?

以下答案的工作代码

@Effect() authenticate$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_REQUEST)
.switchMap(update => this.api.post('/authenticate', update.action.payload)
  .map((res:any) => {
    return {
      res: res,
      update: update
    };
  })
  .do((result:any) => {
    if(result.update.action.payload.remember) {
      this.authService.setAuth(result.res.json());
    }
  })
  .map((result:any) => this.authActions.authenticateSuccess(result.res.json()))
  .catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
);

1 个答案:

答案 0 :(得分:3)

您应该map post观察点可以包含update

@Effect() authenticate$ = this.updates$
  .whenAction(AuthActions.AUTHENTICATE_REQUEST)
  .switchMap(update => this.api.post('/authenticate', update.action.payload).map((res:any) => {
    return {
      res: res,
      update: update
    };
  }))
  .do((result:any) => { ... whatever it is you need to do with result.update ... })
  .map((result:any) => this.authActions.authenticateSuccess(result.res.json()))
  .catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
)