【问题标题】:How to get result of Observer in subscribe?如何在订阅中获得观察者的结果?
【发布时间】:2018-11-10 13:30:49
【问题描述】:

我对服务器有两个Observable 请求:

this.initService.__init__(res).subscribe((profile) => {
    console.log(profile); // It works
    this.initService.initializePeriod(profile).subscribe((period) => {
        console.log(period); // It does not work
    });

});

当第一次得到响应时,它调用第二个,但我无法获得第二个订阅的结果。我知道,在这种情况下最好使用 Promises,但我需要将结果从第一个请求传递到第二个请求,promises 不允许这样做。

我尝试使用它,但警报消息不起作用:

 this.initService.__init__(res)
            .pipe(
              mergeMap(profile => this.initService.initializePeriod(profile)))
              .subscribe((response) => {
              alert('aa');

});

也试过这个:

this.initService.__init__(res)
              .mergeMap(profile => this.initService.initializePeriod(profile))
              .subscribe((response) => {
              alert('aa');
});

【问题讨论】:

    标签: angular rxjs rxjs5


    【解决方案1】:

    您可以使用switchMap rxjs 运算符来链接可观察对象。

    import { switchMap } from 'rxjs/operators';
    
    this.initService.__init__(res)
    .pipe(
       switchMap(profile=> this.initService.initializePeriod(profile))
    ).subscribe((period) => {
        console.log(period);
    });
    

    如果您想得到两者的回应,请使用mergeMap

    import { mergeMap } from 'rxjs/operators';
    
    this.initService.__init__(res)
    .pipe(
       mergeMap(
          profile=> this.initService.initializePeriod(profile), 
         (profile, period) => {
           return [profile,period];
    }
       )
    ).subscribe((response) => {
        console.log(response[0]); //profile
        console.log(response[1]); //period
    });
    

    工作副本在这里 - https://stackblitz.com/edit/typescript-wy26a7

    【讨论】:

    • 好的,如何在上次订阅中传递profile变量?
    • 我看到两个请求都在工作,但我仍然无法得到共同的结果,我做了 alert() 作为响应,但没有得到它
    • 很奇怪的一行:``` profile => this.initService.initializePeriod(profile), (profile, period) => { return [profile, period]; } ```
    • 我试过这个。但警报不起作用:` this.initService.__init__(res) .pipe(mergeMap(profile => this.initService.initializePeriod(profile))) .subscribe((response) => { alert('aa'); `
    • 你看演示了吗?两个结果都来了。
    【解决方案2】:

    您需要检查您从第一次 API 调用(配置文件)中获得的结果。检查您的浏览器控制台。配置文件可能是 JSON,而不是有效的 URL。如果 URL 无效,请求将不会通过。

    如果您提供有效的 URL,则另一个 API 调用中的 API 调用应该可以工作。

    【讨论】:

    • 我检查了这个,都从服务器返回响应
    • 我假设函数调用:initService.__init__ () and initService.initializePeriod() 仅用于最小限度的复制,而您实际上是在那个地方进行 http 调用。这是正确的吗?
    • 我猜问题出在 HTTP 拦截器上,我会检查
    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    相关资源
    最近更新 更多