![](/img/trans.png)
[英]How to convert a Subsink api call to Promise.all within Angular9?
[英]How to handle two api calls in Angular Subsink?
我正在angular subsink
內進行 api 調用,如下所示:
import {SubSink} from 'subsink';
...
...
async clickButton() {
for (let i = 0; i < this.Id.length; i++) {
const hostId = await this.serviceA.Status(this.hostName[i]);
this.subs.sink = this.serviceB.createDbEntry(hostId))
.subscribe(s => {
if (i === this.Id.length - 1) {
this.dialog.close();
}
});
}
}
這里this.Id
是any
類型
現在我想在成功完成this.serviceB.createDbEntry(hostId)
后進行另一個 api 調用,並且我通過添加另一個subs.subsink
來做到這subs.subsink
,如下所示:
import {SubSink} from 'subsink';
...
...
async clickButton() {
for (let i = 0; i < this.Id.length; i++) {
const hostId = await this.serviceA.Status(this.hostName[i]);
this.subs.sink = this.serviceB.createDbEntry(hostId))
.subscribe(s => {
if (i === this.Id.length - 1) {
this.dialog.close();
}
});
this.subs.sink = this.serviceC.runRetry(hostId))
.subscribe(s => {
if (i === thisserverId.length - 1) {
this.dialog.close();
}
});
}
}
這是在this.serviceB.createDbEntry(hostId))
之后關閉對話框而不是調用this.serviceC.runRetry(hostId))
使用 Observable
您可以使用forkJoin
和switchMap
的操作Rxjs
。
檢查forkjoin
文檔以及
檢查switchMap
文檔
通過使用運算符,您可以像這樣重寫代碼
forkJoin(this.hostName.slice(0, this.Id.length).map(hostName => {
return this.serviceA.Status(hostName).pipe(
switchMap(hostId => this.serviceB.createDbEntry(hostId).pipe(map((dbEntry) => ({dbEntry, hostId})))),
switchMap(resp => this.serviceC.runEntry(resp.hostId))
)
})).subscribe(() => this.dialog.close());
使用 Promise
Promise.all(this.hostName.slice(0, this.Id.length).map(hostName =>
this.serviceA.Status(hostName)
.then(hostId => this.serviceB.createDbEntry(hostId).then(() => hostId))
.then(hostId => this.serviceC.runEntry(hostId))
)).then(() => this.dialog.close())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.