Angular 2:使用带有 Observables 的 HTTP 请求来搜索数据库

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

我正在学习 Angular 2 关于使用 HTTP 请求和 Observables 搜索数据库的教程。这里有一个link的具体教程:https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

您可以搜索 "Search-by-name" 以找到我所指的教程区域。

这里是有问题的代码:

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[]>([]);
  });

我能够对此代码进行适当的更改以使其与我的应用程序一起工作,但我想知道如何在成功 returns 数据和无法找到什么时调用函数您正在寻找。做起来可能相对简单,但我很难弄明白,也不太确定如何搜索它。

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

您还需要订阅。在您订阅之前什么都不会发生。

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

在这里您可以处理 "success"、"error" 和 "complete" 案例。 subscribe分别接受这三个回调。

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

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

只需检查来自订阅 "success" 的 heroes 是否为空。