【问题标题】:RxJS switchMap and passing response to another operatorRxJS switchMap 并将响应传递给另一个操作员
【发布时间】:2018-08-04 15:04:10
【问题描述】:

假设我有这样的代码:

            this.apiService.getUrlForPhoto('photo1')
            .switchMap((url) => {
                return this.apiService.uploadPhotoToProvidedUrl(url);
            })
            .switchMap((response) => {
                return this.apiService.confirmPhotoUpload(confirmationToken);
            })
            .subscribe((response) => {
                if (response.confirmed) {
                    console.log('Success');
                }
            });

首先是http get,它返回我可以发布新照片的url, 其次是 http put 我必须上传照片的地方, 第三是 http 帖子,我必须确认照片已上传到该网址。

我的问题是可以将 url 传递给第二个 switchMap 吗?在第二个 switchMap 我有来自 uploadPhotoToProviderdUrl 方法的响应,但是我怎样才能从以前的方法中获得响应?

【问题讨论】:

  • 使用变量怎么样?这不可能吗?
  • 是的,我就是这样做的,但我想知道有没有更好的解决方案?

标签: angular rxjs switchmap


【解决方案1】:

假设你所有的 API 调用都是 Observables:

this.apiService.getUrlForPhoto('photo1')
    .switchMap((url) => {
        return this.apiService.uploadPhotoToProvidedUrl(url)
            .switchMap((response) => {
                // Here you can use 'url'
                return this.apiService.confirmPhotoUpload(confirmationToken);
            })  
    })
    .subscribe((response) => {
        if (response.confirmed) {
            console.log('Success');
        }
    });

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2018-09-18
    • 2020-09-26
    • 2020-04-07
    相关资源
    最近更新 更多