首页 > 解决方案 > 读取参数,然后在 Angular 中查找单个元素

问题描述

我有一个carriersService带有方法的服务getAll(),它返回一个Observable<Carrier[]>. 在我的组件中,我正在尝试读取路由参数carrierId,找到带有此类的运营商carrierId并将其分配给局部变量

let carrier = null;

this.route.paramMap.pipe(
      switchMap(
        (params: ParamMap) => this.carriersService.getAll()));

Carrier[]我需要从使用的 Observable 中找到一个 Carrierparams.get('carrierId')并将其分配给本地运营商变量。

标签: angularrxjsrxjs-observablesrxjs-pipeable-operators

解决方案


combineLatest 将在两个可观察对象都发出后发出,这允许您使用路由参数来查找数组中的载体。

combineLatest(
  this.route.paramMap.pipe(map(p => p.get('carrierId'))),
  this.carriersService.getAll()
).pipe(
  map(([carrierId, carriers]) => carriers.find(carrier => carrier.id === carrierId))
).subscribe(carrier => {
  this.carrier = carrier;
});

推荐阅读