Angular HttpClient combine pipe, tap with subscribe?

13,420

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)})
Share:
13,420
Marc_L
Author by

Marc_L

Software Developer with Java and Javascript and a free time Data Scientist with the Python stack.

Updated on June 30, 2022

Comments

  • Marc_L
    Marc_L almost 2 years

    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?

  • Marc_L
    Marc_L almost 6 years
    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..?
  • John
    John almost 6 years
    If I understand correctly, you can use map inside the pipe like this: .pipe( map(data => { return doSomeLogic;})). Have a look at this question: stackoverflow.com/questions/47275385/… 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 helps