angular - 读取参数,然后在 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')
并将其分配给本地运营商变量。
解决方案
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;
});
推荐阅读
- java - TreeSet 是否有可能等于 HashSet 但 HashSet 不等于 TreeSet
- python - 将相同条件应用于多个列
- sql - SQL - 根据条件按顺序排除项目
- visual-studio-code - 如何从资源管理器中分离大纲
- javascript - 带有中等边框底部的标题 - Bootstrap
- rest - REST API:端点名称冲突和端点路径中的前缀/命名空间/逻辑范围
- android - 在 Kotlin 中创建具有固定大小的对象数组
- angular - 在组件中使用响应结果
- sql - SQL Query 根据条件连接行值
- javascript - 连接四游戏中的输出问题