假设我想通过调用REST API在Angular应用程序中获取数据,以便在Angular应用程序中显示数据。
我会把这样的东西叫做:
this.http.get(this.configUrl).subscribe(response => {
//do something
});然而,我经常遇到这样的情况,我必须根据第一个REST API call.So获取更多数据,我的数据如下所示:
this.http.get(this.configUrl).subscribe(response => {
//next call
this.http.get(this.configUrl).subscribe(response => {
//next call
this.http.get(this.configUrl).subscribe(response => {
//next call
this.http.get(this.configUrl).subscribe(response => {
//do something
});
});
});
});我发现这很难读懂。有没有办法让它在Angular / Typescript中更具可读性,或者我做了一些根本错误的事情?
发布于 2021-05-17 17:34:42
您可以使用管道运算符,如switchMap和 RxJS 来简化此嵌套调用;
this.http.get(this.configUrl)
.pipe(map(
res => res.json()),
switchMap(data => {
const data1 = data.sample_datum;
return this.http.get(this.configUrl + "&data=" + data1);
}),
switchMap(data => {
const data2 = data.sample_datum2;
return this.http.get(this.configUrl + "&data=" + data2);
}),
switchMap(data => {
const data3 = data.sample_datum3;
return this.http.get(this.configUrl + "&data=" + data3);
}),
switchMap(data => {
const data4 = data.sample_datum4;
return this.http.get(this.configUrl + "&data=" + data4);
}))
.subscribe((d) => console.log("subscribe", d))或者您可以使用await关键字来防止嵌套。
const data1 = await this.http.get(this.configUrl);
const data2 = await this.http.get(this.configUrl + "&data=" + data1);
const data3 = await this.http.get(this.configUrl + "&data=" + data2);
const data4 = await this.http.get(this.configUrl + "&data=" + data3);https://stackoverflow.com/questions/67566891
复制相似问题