Rxjs如何调用冷Observables
问题描述:
吹码是来自bookexist护卫ngrx/example 据我所知,它打电话googleBooks
服务做出一个http请求,并检查该书是否已经在商店。我无法理解的部分是它不会在护卫服务的任何地方拨打subscribe
。我的理解是,Anuglar2中的http Observables被认为是冷观察对象,这意味着它们不会被调用,直到有人订阅它。Rxjs如何调用冷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由被称为:
/**
* 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
是角界面,它是由路由器调用。 CanActivate
的实现可以返回一个observable,一个promise或一个boolean。当它返回一个可观察对象时,路由器会订阅它 - 它看到了对它构成的观察值的订阅,并且最终 - 到您在问题中包含的hasBookInApi
返回的可观察值。