【发布时间】:2020-07-22 15:02:44
【问题描述】:
我有一个端点返回{ ids: [1, 2, 3, 45] }。
另一个返回给定 id 的值:{ id: 3, value: 30, active: true }。
我正在尝试构建一个 observable,它调用第一个端点并为每个返回的 id 调用第二个端点并发出所有 active = true 值的总和:
private getIds(group: string) {
const url = '...';
return this.http.get<{ ids: number[] }>(url, { params: { group } });
}
private getValue(id: number) {
const url = '...';
return this.http.get<ActiveValue>(url, { params: { id: id.toString() } });
}
public getSum(group: string) {
let sum = 0;
const bSubject = new BehaviorSubject(sum);
const observables = this.getIds(group).pipe(
mergeMap(({ ids }) => ids),
map(id => this.getValue(id).pipe(tap(({ value, active }) => {
if (active) {
sum += value;
bSubject.next(sum);
}
})))
);
const observable = forkJoin(observables).pipe(map(() => sum));
return { bSubject, observable };
}
interface ActiveValue {
value: number;
active: boolean;
}
但它抱怨:
forkJoin is deprecated: Use the version that takes an array of Observables instead (deprecation)
此外,当我将鼠标悬停在 observables 上时,它会显示:
const observables: Observable<Observable<ActiveValue>>
...虽然我认为应该是Observable<ActiveValue>[]
我怎样才能让它工作?
【问题讨论】:
-
"虽然我认为它应该是 Observable
[]" 你能解释一下你得出这个结论的思考过程吗?为什么你要按照你的方式建造你的管道? (你好像误解了mergeMap和map)
标签: angular typescript rxjs rxjs6