【问题标题】:Monitor HttpClient data - don't post data on subscribe监控 HttpClient 数据 - 不要在订阅时发布数据
【发布时间】:2018-02-12 12:20:53
【问题描述】:

我正在尝试找出一种方法来监视来自 2 个位置的 HttpClient.Post observable 的结果,而不会将数据两次发布到我的服务器。

我在这里创建了一个示例:https://stackblitz.com/edit/angular-aau9mg


目前我有一个app.service,它从服务器获取数据,然后在返回数据时设置一个值:

public getDump():Observable<any> {
    var observable = this.http.get("https://angular-http-guide.firebaseio.com/courses.json");

    observable.subscribe(
      data => this.someValue = 99,
      error => console.log(error)
    );

    return observable;
  }

然后,在app.component 我想禁用发布按钮(dumpInProgress),然后在检索数据时,设置dump

getDump(){
    this.appService.getDump().subscribe(
      (data) => this.dump = data,
      () => { },
      () => this.dumpInProgress = false
    );
  }

因此,目前这完全按预期工作并达到了预期的结果。我遇到的问题是,如果您在单击获取转储按钮时检查网络日志,您将看到请求被发出了两次!这是因为:

直到您对该方法返回的可观察对象调用 subscribe() 后,HttpClient 方法才会开始其 HTTP 请求。这适用于所有 HttpClient 方法。 Source

那么是否有可能在不进行第二次get请求的情况下达到这个结果?

【问题讨论】:

  • 这里真的很晚,早上会回复。
  • 更新了 stackblitz 链接
  • @RahulSingh,他订阅了两次,不是飞行前请求的问题

标签: angular typescript rxjs


【解决方案1】:

我想你只需要map函数:

public getDump():Observable<any> {
    return this.http.get("https://angular-http-guide.firebaseio.com/courses.json").map(
        data => { this.someValue = 99; return data; },
        error => console.log(error)
    );  
}

2 个请求背后的原因是,

this.appService.getDump().subscribe(...)
observable.subscribe(...)

这 2 行代码,您通过订阅两次来进行 2 次调用 .

WORKING DEMO

【讨论】:

  • 是的,我通过双重订阅解决了这个问题。这是我有过的最快的正确答案!你搞定了,谢谢!
  • @Zze,感谢您的赞赏,BTW 编码快乐 :)
猜你喜欢
  • 2021-05-06
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
相关资源
最近更新 更多