我创建了一个设置服务,其中包含2个BehaviorSubject,如下所示:
settingNameSubject = new BehaviorSubject<SettingName>({});
SettingDataSubject = new BehaviorSubject<SettingData>({});
<SettingData>
包含对象列表,每个对象都有一个<SettingName>
。
我必须创建一个“设置名称可观察”的属性,该属性只能订阅settingNameSubject,并返回在SettingDataSubject中找到的值。
我使用了CombineLastest:
this.SettingName$ = this.SettingNameSubject.asObservable();
this.combinedOne = combineLatest(this.SettingName$, () => {
return this.SettingDataSubjectValue.filter(item => item.name === this.SettingName$.getValue())
});
有没有解决问题的不同方法?
如果我想同时订阅两个BehaviorSubject,我应该使用CombineLatest2吗?
答案 0 :(得分:0)
也许使用switchMap更直观
settingNameSubject.pipe(switchMap(name=>
this.SettingDataSubject.pipe(filter(item => item.name === name))
))
答案 1 :(得分:0)
在用户在一个页面上选择一个产品而另一页面上的产品详细信息发生更改时,我有类似的事情。我只用这样一个BehaviorSubject来做到这一点:
private productSelectedSubject = new BehaviorSubject<number>(0);
// Expose the action as an observable for use by any components
productSelectedAction$ = this.productSelectedSubject.asObservable();
selectedProduct$ = combineLatest([
this.products$,
this.productSelectedAction$
]).pipe(
map(([products, selectedProductId]) =>
products.find(product => product.id === selectedProductId)
),
tap(product => console.log('selectedProduct', product)),
shareReplay(1)
);
products$
流包含数据:
products$ = this.http.get<Product[]>(this.productsUrl)
.pipe(
tap(data => console.log('Products', JSON.stringify(data))),
catchError(this.handleError)
);
所以我将动作流(BehaviorSubject)与数据流(通过http.get获取)组合在一起
由于详细信息页面已订阅selectedProduct$
,因此每次向productSelectedAction$
流发送项目时,该页面都会自动更新。
不需要用另一个BehaviorSubject通知它。
有道理吗?