[英]How to handle two api calls in Angular Subsink?
I am making an api call within angular subsink
as follows:我正在
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();
}
});
}
}
Here this.Id
is of type any
这里
this.Id
是any
类型
Now I want to make another api call after the successful completion of this.serviceB.createDbEntry(hostId)
And, I am doing it by adding another subs.subsink
as below:现在我想在成功完成
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 is closing the dialog box after this.serviceB.createDbEntry(hostId))
and not calling this.serviceC.runRetry(hostId))
这是在
this.serviceB.createDbEntry(hostId))
之后关闭对话框而不是调用this.serviceC.runRetry(hostId))
With Using Observables使用 Observable
You can use forkJoin
and switchMap
operator of Rxjs
.您可以使用
forkJoin
和switchMap
的操作Rxjs
。
Check documentation of forkjoin
and also检查
forkjoin
文档以及
Check documentation of switchMap
检查
switchMap
文档
With using the operators you can rewrite your code like通过使用运算符,您可以像这样重写代码
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());
With Using Promises使用 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.