我正在Angular 9
中进行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.serviceC.runRetry(hostId)
之后再进行一次API调用this.serviceB.createDbEntry(hostId))
而且,我通过如下添加forkJoin
来做到这一点:
import {forkJoin} from 'rxjs';
import {switchMap} from 'rxjs/operators';
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());
serviceA Status
具有以下实现:
public status<T>(host: string) {
const hostString = host.toString();
const Url = `${this.api}/${hostString}`;
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return this.http.get<rData<T>>(Url).toPromise();
}
我收到如下警告:
forkJoin Deprecated symbol used, consult docs for better alternative deprecated export function forkJoin<any>( sources: any):Observable<unknown[]>
我也遇到错误:
TS2339: Property 'pipe' does not exist on type 'Promise >'.
答案 0 :(得分:0)
这里:
const hostId = await this.serviceA.Status(this.hostName[i]);
和
return this.serviceA.Status(hostName).pipe( //...
在第一行中,您将serviceA.Status()
视为应许。在第二篇中,您将其视为可观察的。我假设第一个是正确的(来自错误消息)。快速解决:使用from
运算符将承诺转换为可观察的内容。 好修复:不要将promise范式与RxJS范式混合,坚持一个(最好是坚持Rx),否则它有可能变得真正混乱。