Search code examples
angularangular2-observables

Angular 2: Using HTTP requests with Observables to search a database


I'm following Angular 2's tutorial on using HTTP requests with Observables to search a database. Here is a link to the specific tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

You can do a search for "Search-by-name" to find the area of the tutorial I'm referring to.

Here is the code in question:

this.heroes = this.searchTerms
  .debounceTime(300)        // wait for 300ms pause in events
  .distinctUntilChanged()   // ignore if next search term is same as previous
  .switchMap(term => term   // switch to new observable each time
    // return the http search observable
    ? this.heroSearchService.search(term)
    // or the observable of empty heroes if no search term
    : Observable.of<Hero[]>([]))
  .catch(error => {
    // TODO: real error handling
    console.log(error);
    return Observable.of<Hero[]>([]);
  });

I was able to make appropriate changes to this code to get it to work with my application, but I am wondering how to invoke functions for when it successfully returns data and when it is unable to find what you're looking for. It's probably relatively simple to do, but I'm having trouble figuring it out and am not quite sure how to search for it.


Solution

  • I am wondering how to invoke functions for when it successfully returns data and when it is unable to find what you're looking for

    You still need to subscribe. Nothing happens until you subscribe.

    this.searchTerms
      .debounceTime(300)  
      .distinctUntilChanged()
      .switchMap(term => term  
        ? this.heroSearchService.search(term)
        : Observable.of<Hero[]>([]))
      .catch(error => {
        return Observable.of<Hero[]>([]);
      })
      .subscribe(heroes => {
        this.heroes = heroes;
        doOtherStuff();
      });
    

    This is where you can handle "success", "error", and "complete" cases. The subscribe takes these three callbacks, respectively.

     .subscribe(
       (heroes) => {},  // success
       (error) => {},   // error
       () => {}         // completed/always
     );
    

    when it is unable to find what you're looking for

    Just check if the heroes from the subscribe "success" is empty.