angular - 在 pipe() 链中合并两个 observables
问题描述
我正在使用 Rxjs,我想从以下模式(按顺序)创建一个 Observable:
从 paramMap$ 获取参数,然后...
根据 params 的值,将两者 (getData():Observable, getCategories():Observables) 放在一起,然后......
from ([data, categories]) 创建最终对象。
代码如下所示:
//route = this.ActivatedRoute
let obs$ = route.paramMap.pipe(
// combineLatest() is not a pipable operator, so it shouldn't be used inside .pipe()
// also it doesn't accept a function,
// but this just to show you what I want to do.
combineLatest(params=>getData(params.id), params=>getCategories(params.id)),
map(([data, categories])=>{
//do some changes...
return {data,categories}
}
)
)
将此代码放在 Angular 项目中的最佳位置是哪里:
constructor()
不是最佳实践,因为这是一个长时间运行的操作(实际上它必须执行 API 请求)ngOnInit()
不推荐,因为在某些时候我必须更改this.params
模板中使用的
...
combineLatest(params=>
getData(params.id).pipe(
map(data=>{
this.params.type=data.type;
return data
})),
params=>getCategories(...)
)
在模板中:
<div>{{params.type}}</div>
解决方案
要在获取参数后对 Observable 进行管道传输,您可以在其中使用switchMap
并返回 a forkJoin()
。
this.route.paramMap.pipe(switchMap((params) => {
return forkJoin(getData(params.id), getCategories(params.id));
}));
我相信,订阅一个 Observable,做 API 请求,最好都应该去ngOnInit()
除非你有一些非常具体的要求,在组件加载时你不希望这些订阅。
就this.params
目前而言,您可以this.params
在使用管道tap()
或订阅此 Observable 的地方进行分配。
推荐阅读
- machine-learning - 如何在“sklearn”管道中缩放/估算张量以输入到 Keras LSTM
- node.js - 节点.js | BAD_REQUEST 错误突然出现
- pointers - bss中的静态指针溢出
- git - 克隆时自动包含回购所有者的姓名
- c++ - MSVC:具有非静态存储持续时间的变量不能用作非类型参数
- android - Android - 如何检查 Worker 在入队时是否满足约束?
- android - BOOT_COMPLETED 上的接收器未触发
- ios - 使用 decodeObject(of: forKey:) 解码符合协议的对象
- xaml - 在 UWP XAML 中强制显示效果
- functional-programming - 如何在 ELM 中重构此功能?