【问题标题】:rxjs with angular 2 - how to chain observable streamrxjs with angular 2 - 如何链接可观察流
【发布时间】:2016-08-18 22:52:58
【问题描述】:

我正在使用 angular2 和 @ngrx/store 制作一个应用程序...我是 rxjs 的新手,并以一种反应式的方式思考...真的很苦恼如何链接可观察对象。

我有一个身份验证效果...目前看起来像

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

我想做的是在请求成功时链接两个额外的操作。

  1. 使用this.router.navigate(['/'])成功后导航到“主页”。
  2. 将凭据存储在 LocalStorage 服务 this.authService.store(credentials)

我需要做什么才能将这些操作合并到流中?

【问题讨论】:

  • 您正在调度一个 authenticateSuccess 操作,因此您应该以另一种效果来处理它。当您有多种身份验证方式时,这尤其有用。

标签: angular rxjs


【解决方案1】:

假设最后 2 条语句的执行顺序无关紧要,您所需要做的就是在当前语句的末尾追加

.flatMap(() =>
{
   this.router.navigate(['/']);
   this.authService.store(credentials);
});

【讨论】:

  • 谢谢...好的,会试一试的。是在.switchMap 之后吗?还是在抓到之后?
  • 是的,在 .switchMap 之后
  • 这样做会导致 TypeScript 错误...Argument of type '() => void' is not assignable to parameter of type '(value: Action, index: number) => Subscribable<{}> | Promise<{}> | ArrayLike<{}>'.
  • 我的错。 flatMap 需要被链接到一个 Observable 但你似乎有一个承诺。我会将 this.api.post 调用封装在一个 Observable 中,或者更好地让它返回一个 Observable。然后将 flatMap 链接到该 Observable。
【解决方案2】:

最好的解决方案是保持您的effect 像这样,并添加另一个以对这样的成功操作做出反应:

@Effect({dispatch: false}) authenticateSuccess$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_SUCCESS)
.do(credentials => {
    this.router.navigate(['/']);
    this.authService.store(credentials);
});

{dispatch: false} 的意思是“对这个动作做出反应但不发送另一个”。

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 2018-10-25
    • 2021-08-26
    • 1970-01-01
    • 2021-01-11
    • 2020-09-10
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多