Angular HttpClient combine pipe, tap with subscribe?
Asked Answered
A

1

5

I am trying to retrieve some data with HttpClient in Angular. My code looks like as follows:

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)})
    )
  }

However, I cannot use subscribe in the pipe method, or chain it before or after the .pipe method. The problem is, that without subscribe, it seems this code is not returning any data from the url or logging anything to the console although the link and the data exists?

Approximal answered 6/7, 2018 at 8:52 Comment(4)
The service should NOT subscribe. The caller of this service should. angular.io/guide/http And why, oh why are you using any? Wouldn't it be nice to know what the array actually contains?Dybbuk
actually, I have this "service" in my component as a method, so the caller is actually the one who subscribes... but I did it now in NgOnInit()...Approximal
Well, don't do that. Put your data access code in a service. angular.io/guide/httpDybbuk
+1 Always bubble up the asynchronicity to the caller as far as you can and use it there! Off-topic: Oh dear, it seems every time I answer one of these async Promise Observable or http.request questions another pops up. Staunch the bleeding! Bail out!Shebat
A
14

You must subscribe to the method (since it returns an Observable), not inside the pipe.

Try this instead

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',[])),
    )
  }

then make a call

this.getData("url").subscribe(Response => { console.log(Response)})
Akee answered 6/7, 2018 at 8:55 Comment(2)
ok thanks, this solved my problem, now I have the data in the Response, what would I do now when I wanted to do data processing with e.g. .map() functions? can I chain the function map anywhere before or after subscribe? And secondly, why can't I subscribe directly after the method, this was the case with the old Http library, you used it by doing a get query followed by a .subscribe method... I was just wondering why they did it different this time with the new HttpClient..?Approximal
If I understand correctly, you can use map inside the pipe like this: .pipe( map(data => { return doSomeLogic;})). Have a look at this question: #47275885 I am not sure I understand the second question about subscribing directly. You can subscribe directly in your getData()-function, by using .pipe().subscribe(). However, you will then return a Subscription, not an Observable. Hope that helpsAkee

© 2022 - 2024 — McMap. All rights reserved.