【问题标题】:Can't combineLatest using router state in Angular无法在 Angular 中使用路由器状态组合最新
【发布时间】:2017-12-14 22:13:12
【问题描述】:

我正在尝试使用 Ngrx 中的 combineLatest 在导航端执行操作,或在另一个订阅中更改状态。在我的组件的ngOnInit() 中,我有:

ngOnInit(): void {
    const routerSub = this.router.events.subscribe();
    const patientSub = this.patientService.state.subscribe();

    Observable.combineLatest(routerSub, patientSub, (routerEvent, patientState) => {
      console.log(routerEvent);
      console.log(patientState);
    });
  }

但是,我在routerSub 上有一个编译器错误:

“订阅”类型的参数不能分配给类型参数 '调度程序 |订阅 |承诺喜欢 | ArrayLike | ((...values: any[]) => {})'

我应该为combineLatest 提供路由器状态什么?

【问题讨论】:

标签: angular ngrx


【解决方案1】:

combineLatest 结合observables 并在所有可观察对象都具有要发出的最新值时发出最新值。所以你需要传入 observables,而不是订阅。所以你的代码应该改为

ngOnInit(): void {
    const routerSub = this.router.events;
    const patientSub = this.patientService.state;

    Observable.combineLatest(routerSub, patientSub, (routerEvent, patientState) => {
      console.log(routerEvent);
      console.log(patientState);
    })
    .subscribe();

}

【讨论】:

  • 啊 - 我也错过了最后的.subscribe()。但是,如果我按照以下示例进行操作:netbasal.com/rxjs-six-operators-that-you-must-know-5ed3b6e238a0,我永远不会看到发出任何值。我知道状态已填充,因为还有其他利用 patientState 的组件可以正常工作。只有在导航之后,我才能看到发出的值。无论我是否导航,我都期待看到最新的patientState
  • @Brandon combineLatest 在您首次订阅时不会触发初始发射。因此,在其中一个可观察对象发出之前,您不会获得最新的值。
  • 嗯。还有其他运营商会吗?还是更好的方法?
  • @Brandon 抱歉,我弄错了。 combineLatest will 在订阅 if 上发出,这两个 observable 都有一个要发出的最新值。所以听起来正在发生的事情是您的状态确实具有最新值,但 router.events 没有。这就是为什么当你导航时,现在两个 observables 都有一个最新的值并且 combineLatest 发出。因此,如果任一 observable 具有最新值,则您正在寻找在订阅时发出的东西,然后在任一 observable 发出时发出?
  • 我实际上最终使用了race。我将您的答案标记为已接受,因为它确实解决了我的编译问题:)
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 2021-07-03
  • 2018-11-26
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
相关资源
最近更新 更多