Home  >  Forum  >  Angular
Post New Query

Observable.subscribe in Angular 2



Asked on September 07, 2017
Expalin working of Observable.subscribe in Angular 2 code

 this.observableBooks = this.bookService.getBooksWithObservable();
	this.observableBooks.subscribe(
            books => this.books = books,
            ...
I'am unable to understand the subscribe method , are there any useful resources for learning this 



Replied on September 07, 2017
subscribe is a RxJS operator.  When we subscribe to Observable instance, only when the URL hits to server. 
Suppose getBooksWithObservable() is given as below

getBooksWithObservable(): Observable<Book[]> {
    return this.http.get(this.url)
        .map(this.extractData)
        .catch(this.handleErrorObservable);
}
And if we call this method as given below

this.observableBooks = this.bookService.getBooksWithObservable();

It returns the instance of Observable but still  this.http.get(this.url) has not run. No connectivity with server yet. Actual hit to server goes in two cases.

1. Subscribe to Observable instance observableBooks  using subscribe() method.

this.observableBooks.subscribe(
            books => {
               //Data from server has been received.
               //perform operation on books
           }
      );

Now  this.http.get(this.url) will run and response will be received inside subscribe() method. If we want to perform any task only after data has been received from server, we need to code it inside subscribe() method.

2. Using Async Pipe on observableBooks instance.

  <li *ngFor="let book of observableBooks | async" >
    Id: {{book.id}}, Name: {{book.name}}
  </li>

Find the URL for Async Pipe.




Write Answer








©2019 concretepage.com | Privacy Policy | Contact Us