我需要你在 RxJS 方面的帮助。
我制作了这段代码,这是获取 API 所需的代码,对于返回的元素,从另一个 API 获取此元素类型。 这段代码工作正常,但它返回一个 Observable 的 'type' 属性,而不是只返回“string”。你知道如何实现这一目标吗?非常感谢。
combineLatest([
this.service.list().pipe(
map(items =>
items.map(item => {
item['type'] = this.getType(item.id);
return item;
})
),
map(items => items.map(item => ({
id: item.id,
type: item['type'],
})))
),
this.form.valueChanges,
]).subscribe()
答案 0 :(得分:1)
您将 Observable
分配给属性而不是它的响应。您需要将 RxJS forkJoin
和 Array#map
与高阶映射运算符(如 switchMap
)一起使用。
试试下面的方法
combineLatest([
this.service.list().pipe(
switchMap((items: any) => // <-- switch to another observable
forkJoin( // <-- multiple parallel requests
items.map(item =>
this.getType(item['id']).pipe(
map((type: any) => ({ // <-- map back to original item with added type
...item,
type: type
}))
)
)
)
)
),
this.form.valueChanges,
]).subscribe()