微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Promise中正确使用forkJoin和switchMap来调用两个API?

如何解决如何在Promise中正确使用forkJoin和switchMap来调用两个API?

我正在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 >'.

解决方法

这里:

const hostId = await this.serviceA.Status(this.hostName[i]);

return this.serviceA.Status(hostName).pipe( //...

在第一行中,您将serviceA.Status()视为应许。在第二篇中,您将其视为可观察的。我假设第一个是正确的(来自错误消息)。快速解决:使用from运算符将承诺转换为可观察的内容。 修复:不要将promise范式与RxJS范式混合,坚持一个(最好是坚持Rx),否则它有可能变得真正混乱。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。