【问题标题】:Rxjs how to invoke cold ObservablesRxjs 如何调用冷的 Observables
【发布时间】:2017-03-16 04:26:50
【问题描述】:

blow 代码来自ngrx/example 中的 bookexist 路由守卫 我知道它正在调用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);
    });
}

【问题讨论】:

    标签: rxjs angular2-http angular2-observables


    【解决方案1】:

    它是通过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 的实现可以返回 observable、promise 或 boolean。当它返回一个 observable 时,路由器会订阅它 - 它会看到对其中组成的 observable 的订阅,并最终 - 订阅您在问题中包含的 hasBookInApi 返回的 observable。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      相关资源
      最近更新 更多