-1

I have this method in the component:

saveItem() {
   return this.itemService.updateItem(this.item)
     .pipe(
       tap((data: any) => {
         this.toastr.success('Saved');
       }),
       catchError((error: any) => {
       return throwError(error.error);
      }
    )
  )
}

And this is the function inside the itemService:

updateItem(item: Item) {
    return this.http.post<any>(this.updateItemUrl, {
        item: item
    });
}

If I put a breakpoint inside the saveItem() on the line 'return this.itemService.updateItem(this.item)', and if I put a breakpoint inside the updateItem() on the line 'return this.http...', it correctly goes and stop into the breakpoints... But I have the following issue: the rest-api calling is not triggered, and the http call is not sent.. in fact, if a I put a breakpoint inside the .pipe() operator, it doesn't go inside. Why?

Matt Stobbs
  • 611
  • 2
  • 8
  • 21
panagulis72
  • 2,129
  • 6
  • 31
  • 71

1 Answers1

4

Observables (like http-Requests) get only active when they have at least one subscriber.

=> No Subscriber => No Http-Request

You can subscribe explicitly by

myObservable.subscribe()

or implicitly by the async pipe in the html template

<span> {{ myObservable | async }} </span>

warm regards

JanRecker
  • 1,787
  • 13
  • 17
  • I added: .pipe( ........ ) .subscribe((data: any) => { console.log(data); })' So the .pipe() operator is useless? Where should I put the logic of the show toaster/return error? – panagulis72 Jul 19 '18 at 09:31
  • 2
    the 'pipe(....)' operator is for doing operations on the stream. They operate onthe stream, but they do not "start" it. – JanRecker Jul 19 '18 at 10:11
  • So for example if the service gives me back the number 2, and I want to duplicate it before to show it into the View, I should use pipe() and then maybe a map() to duplicaticate the number, and then with the 'subscribe' I just return back the formatted result to the View? Or it is useless, and I should duplicate it directly into the .subscribe()? Or is it the same? – panagulis72 Jul 19 '18 at 10:15
  • From the result it is the same. But sometimes you may want to provide a method that returns an observable. Then you would use the pipe in the method. As a result, for those who subscribe to your method all will get the "modified" data. Also, i personaly like to move all data manipulation into the pipe and make use of the pipe methods (map, tap,...). I think that my code gets better readable by that. – JanRecker Jul 24 '19 at 06:16