[英]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.