【问题标题】:RxJS / Angular 2 / @ngrx/store /effects how to combine actionsRxJS / Angular 2 / @ngrx/store /effects 如何组合动作
【发布时间】:2016-12-28 10:13:20
【问题描述】:

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

@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 请求已成功返回...但如果出现错误显然不会。 p>

如何在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)))
);

【问题讨论】:

  • 我可以想到一两种方法来做到这一点,但它们会很老套。最干净的方法(恕我直言)是让 rememberMe 字段在 API 响应中返回 - 这对您来说可能吗?
  • 那肯定是最干净的,但不幸的是我无法控制后端返回的内容..

标签: angular rxjs


【解决方案1】:

你应该能够map post observable 包含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)))
)

【讨论】:

  • 谢谢@cartant!这就是我想要做的! (只需要从 .switchMap 末尾删除多余的括号)
  • 这不起作用 - switchMap() 的参数需要返回一个 Observable,这里不是这种情况。
  • 啊,好吧,我看的不够仔细。你是对的,很好的答案:+1。不过,作为记录,您可以将 ((res:any)=>{return {res: res, update:update}}) 替换为 ((res:any)=>({res: res, update:update}))。请注意,对象字面量用括号括起来 :-)
猜你喜欢
  • 2016-12-30
  • 2017-11-19
  • 1970-01-01
  • 2019-07-24
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
相关资源
最近更新 更多