【问题标题】:Angular ngrx - and Router.Events inside Rxjs combineLatest doesn't workAngular ngrx - 和 Rxjs combineLatest 中的 Router.Events 不起作用
【发布时间】:2021-08-03 15:14:40
【问题描述】:

我遇到了一个我无法解决的问题:

onSelectCompany() {
 combineLatest([this.idCompany$, this.idUser$, this.router.events]).subscribe(res => {
   if(res[2] instanceOf NavigationEnd){
     this.router.navigateByUrl(`get-info/${res[0]/res[1]`)
   }
 })
}

我在我的组件的 ngOnInit 上调用了这个函数,我有两个 observables,我需要像我的 url 的参数,只有当我没有刷新页面时,我才需要在这个 url 上导航。但是我写的函数不起作用,我没有错误但是在调试中执行没有进入订阅。为什么?

【问题讨论】:

  • 所有 3 必须在该函数执行后发出一些东西
  • 而不是,如果我删除 this.router.events 它可以工作...问题是 router.events 可观察...我不明白为什么
  • 是的,因为 router.events 只会在有路由事件时发出一些东西
  • 所以,在这种情况下我不能使用 combineLatest
  • 我用“解决方案”更新了我的答案

标签: angular typescript rxjs observable ngrx


【解决方案1】:

所有 3 个 observables 必须在该函数执行后发出一些东西。

来源:https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest

Be aware that combineLatest will not emit an initial value 
until each observable emits at least one value.

一种解决方案可能是将函数从ngOnInit 移动到字段级别或构造函数

【讨论】:

    【解决方案2】:

    您可以通过使用startWith 运算符来模拟路由器事件来绕过它。如果您对 combineLatest 结果进行解构,而不是使用索引访问它,这对您来说也会更容易。

    onSelectCompany() {
     const helper$ = this.router.events.pipe(startWith(null)); // or some other 'safe' value
     combineLatest([this.idCompany$, this.idUser$, helper$])
     .subscribe(([ companyId, userId, routerEvent ]) => {
     // destructure the res array and access the values with variable names
       if(routerEvent instanceOf NavigationEnd){
         this.router.navigateByUrl(`get-info/${companyId}/${userId}`)
       }
     })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 2017-06-25
      • 2018-11-05
      • 2020-06-24
      • 2018-08-14
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      相关资源
      最近更新 更多