【问题标题】:Angular HttpClient combine pipe, tap with subscribe?Angular HttpClient结合管道,点击订阅?
【发布时间】:2018-12-14 19:59:13
【问题描述】:

我正在尝试使用 Angular 中的 HttpClient 检索一些数据。我的代码如下所示:

getData(suffurl: string, id?:number): Observable<any[]> {
    return this.http.get<any[]>('localhost:5555/DNZ/'+ this.suff_url)
    .pipe(
      tap(data => console.log("Anlagenstatus Daten:", data)),
      catchError(this.handleError('getData',[])),
      subscribe(Response => { console.log(Response)})
    )
  }

但是,我不能在 pipe 方法中使用 subscribe,或者在 .pipe 方法之前或之后链接它。问题是,如果没有订阅,尽管链接和数据存在,但似乎这段代码没有从 url 返回任何数据或将任何内容记录到控制台?

【问题讨论】:

  • 服务不应订阅。该服务的调用者应该。 angular.io/guide/http 为什么,哦,你为什么使用any?知道数组实际包含什么不是很好吗?
  • 实际上,我的组件中有这个“服务”作为方法,所以调用者实际上是订阅者......但我现在在 NgOnInit() 中做到了......
  • 好吧,不要那样做。将您的数据访问代码放入服务中。 angular.io/guide/http
  • +1 始终尽可能地向调用者提出异步并在那里使用它! 题外话:哦,亲爱的,似乎每次我回答其中一个async Promise Observable 或http.request 时都会弹出另一个问题。止血!救命!

标签: angular publish-subscribe angular-httpclient


【解决方案1】:

您必须订阅该方法(因为它返回Observable),而不是在管道内。

试试这个

getData(suffurl: string, id?:number): Observable<any[]> {
    return this.http.get<any[]>('localhost:5555/DNZ/'+ this.suff_url)
    .pipe(
      tap(data => console.log("Anlagenstatus Daten:", data)),
      catchError(this.handleError('getData',[])),
    )
  }

然后拨打电话

this.getData("url").subscribe(Response => { console.log(Response)})

【讨论】:

  • 好的,谢谢,这解决了我的问题,现在我在响应中有数据,当我想用​​例如数据处理时我现在该怎么办? .map() 函数?我可以在订阅之前或之后将函数映射链接到任何地方吗?其次,为什么我不能在方法之后直接订阅,旧的 Http 库就是这种情况,您通过执行 get 查询和 .subscribe 方法来使用它......我只是想知道他们为什么这样做不同这次使用新的 HttpClient..?
  • 如果我理解正确,您可以像这样在管道内使用地图:.pipe( map(data =&gt; { return doSomeLogic;}))。看看这个问题:stackoverflow.com/questions/47275385/…我不确定我是否理解关于直接订阅的第二个问题。您可以使用 .pipe().subscribe() 直接在 getData() 函数中订阅。但是,您将返回 Subscription,而不是 Observable。希望有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 2020-11-13
  • 2020-02-15
  • 1970-01-01
相关资源
最近更新 更多