现在对于标题中提到的操作我有以下代码
from(["url_1", "url_2"])
.pipe(
concatMap(url=> this.vocabularyService.getSimilarProducts(url)
.pipe(concatMap(x => x.items))
),
toArray()
)
.subscribe(res => console.log(res));
它的作用是,对于 URLs 数组中的每个 URL,它会进行 API 调用,返回类似这样的内容
class Response {
items: Object[] // this is a specific type, but let's omit this for simplification
}
收到响应后,我再次需要执行
concatMap()
来检索每个 items
数组 item
,最终我执行 toArray()
将每个 item
扁平化为单个数组并将其记录到控制台。
RxJ 是否有任何特定的运算符来执行此类操作,或者是否可以避免我堆叠
concatMap()
运算符?
reduce
像这样展平数组。
import { Component } from "@angular/core";
import { from, of } from "rxjs";
import { concatMap, reduce } from "rxjs/operators";
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
subscripber = {
next: (i) => console.log(i),
complete: () => console.log('end'),
};
ngOnInit() {
from(['url_1', 'url_2'])
.pipe(
concatMap((url) =>
of({
items: [1, 2, 3],
})
),
reduce((acc, one) => {
acc.push(...one.items);
return acc;
}, [])
)
.subscribe((res) => console.log(res));
// Open the console in the bottom right to see results.
}
}