【问题标题】:rxjs: returning value with pipe(map)rxjs:用管道(地图)返回值
【发布时间】:2018-05-16 15:34:49
【问题描述】:

在使用管道和地图时如何返回值,例如在这种情况下:

return this.service.someEvent().pipe(
  map(x => {
    return this.service.someValue;
  })
)

但该值永远不会返回,因为从未订阅过该事件,如果我这样使用它:

const a = this.service.someEvent().pipe(
  map(x => {
    return this.service.someValue;
  })
)

return a.subscribe();

我得到一个错误(我知道这是错误的)。

TS2322: Type 'Subscription' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.   Type 'Subscription' is not assignable to type 'Promise<boolean>'.     Property 'then' is missing in type 'Subscription'.

所以我需要 i 方法来返回值。

更新: 更好的描述(我需要用最新版本的 rxjs 复制这段代码):

canActivate(next: ActivatedRouteSnapshot,
               state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.service.something().map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  })

}

需要在管道内使用地图(据我了解)。

【问题讨论】:

  • 这看起来像你试图在一个方法中调用return a.subscribe();,其类型表明它应该返回Observable。函数subscribe() 返回Subscription 实例

标签: javascript angular rxjs reactivex


【解决方案1】:

您可以简单地从“canActivate”守卫中返回可观察对象本身:-

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.service.something().pipe(map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  }));
}

只有在返回的 observable 完成并且其发出的值为 true 后,路由才会继续。所以你实际上不必担心订阅那个可观察的角度路由器会自己处理它。

【讨论】:

  • 是当 observable 完成时还是当 observable 接收到下一个值时?我认为是后者?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多