【发布时间】:2021-11-28 00:08:24
【问题描述】:
我有一个包含对象数组的 Observable,我想使用第二个 observable 将它们转换为不同的对象。这是一个更大项目的一部分,因此为了简化我的问题,我将有一个具有数字数组的可观察对象,我想将它们转换为字符串。我从以下开始。
const response$ = of({results: [1, 2, 3]});
response$.pipe(
map((response) => {
return response.results.map((id) => {
return id.toString();
})
})
)
.subscribe((response: string[]) => {
console.log(response);
})
订阅中的响应将是预期的字符串数组。现在我需要使用第二个 observable 将数字转换为字符串(再次只是为了让问题更简单)。所以我用return of(id.toString()) 替换了return id.toString() 来模拟对可观察对象的第二次调用。
const response$ = of({results: [1, 2, 3]});
response$.pipe(
map((response) => {
return response.results.map((id) => {
return of(id.toString());
})
}),
)
.subscribe((response: Observable<string>[]) => {
})
现在响应的签名是Observable<string>[],但我需要响应是string[],所以我开始阅读其他 RxJS 运算符,最终得到以下结果。
const response$ = of({results: [1, 2, 3]});
response$.pipe(
concatMap((response) => {
return response.results.map((id) => {
return of(id.toString());
})
}),
concatAll()
)
.subscribe((response: string) => {
console.log('bar', response);
})
我使用了concatMap() 和concatAll(),因为我需要依次调用第二个可观察对象。现在的问题是我的响应是一个字符串,我接到三个电话给订阅者“1”“2”“3”。我需要string[] 的回复。在我的示例中,有人可以解释如何获取 Observable<string>[] 并将其转换为 Observable<string[]> 吗?
【问题讨论】:
标签: rxjs-observables