Rxjs 如何调用冷 Observables

Rxjs how to invoke cold Observables

blow代码来自ngrx/example中的bookexist route guard 我知道它正在调用 googleBooks 服务来发出 http 请求并检查这本书是否已经在商店中。我无法理解的部分是它没有在警卫服务的任何地方调用 subscribe 。我的理解是 Anuglar2 中的 http Observables 被认为是冷 Observables,这意味着它们不会被调用,直到有人订阅它。

我的问题是:下面的 googleBooks 服务是如何被调用的?

hasBookInApi(id: string): Observable<boolean> {
  return this.googleBooks.retrieveBook(id)
    .map(bookEntity => new book.LoadAction(bookEntity))
    .do((action: book.LoadAction) => this.store.dispatch(action))
    .map(book => !!book)
    .catch(() => {
      this.router.navigate(['/404']);
      return of(false);
    });
}

它是通过 the CanActivate implementation:

中组成的 observable 调用的
/**
 * This is the actual method the router will call when our guard is run.
 *
 * Our guard waits for the collection to load, then it checks if we need
 * to request a book from the API or if we already have it in our cache.
 * If it finds it in the cache or in the API, it returns an Observable
 * of `true` and the route is rendered successfully.
 *
 * If it was unable to find it in our cache or in the API, this guard
 * will return an Observable of `false`, causing the router to move
 * on to the next candidate route. In this case, it will move on
 * to the 404 page.
 */
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
  return this.waitForCollectionToLoad()
    .switchMap(() => this.hasBook(route.params['id']));
}

CanActivate 是一个 Angular 接口,由路由器调用。 CanActivate 的实现可以 return 一个可观察对象、一个承诺或一个布尔值。当它 return 是一个 observable 时,路由器会订阅它 - 它会看到对其中包含的 observable 的订阅,并且 - 最终 - 由 hasBookInApi 编辑的 observable return已包含在您的问题中。