【问题标题】:MergeMap and ForkJoin return dataMergeMap 和 ForkJoin 返回数据
【发布时间】:2020-05-13 17:41:52
【问题描述】:

我正在尝试使用 mergeMap 和 forkJoin 进行嵌套的 http 调用。

我想调用一个 API -> 再进行两次内部 api 调用。发送第一个 API 和内部 API 的响应。

我有以下代码

    testmethod(): Observable<Gen | Observable<[UserForm, OtherForm]>> {
        return this.http.get<Gen>("http://test/genData")
        .pipe(
            map(data => {
                const genericData = data;
                return genericData;
            }),
            mergeMap(data => {
                const url1 = data.url1;
                const url2 = data.url2;
                const user = this.http.get<UserForm>(url1);
                const other = this.http.get<OtherForm>(url2);
                return [data, forkJoin<UserForm, OtherForm>([user, other])];
           })
        )
    }

ts文件

    this.service.testmethod().subscribe(item => {
        console.log('test(): ', item);
    }

输出:

    test(): {...}
    test(): Observable

两个 test() 被记录到控制台。我想通过 subscribe 方法获取数据。

我这样做是否正确。从服务返回时我需要更改什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    mergeMap 你应该总是返回一个 Observable,在这里你返回一个数组。

    您可以将您的退货声明修改为:

    return forkJoin<Gen, UserForm, OtherForm>([of(data), user, other]);
    

    【讨论】:

    • 感谢 Ashish,它的工作。一旦允许,我会接受答案。
    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2017-12-09
    相关资源
    最近更新 更多