打击代码来自ngrx/example中的bookexist路线卫
我知道它正在调用googleBooks
服务来发出http请求并检查该书是否已经存储在商店中。我无法理解的部分是它没有在警卫服务中的任何地方调用subscribe
。我的理解是,Anuglar2中的http 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);
});
}
答案 0 :(得分:3)
通过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
是一个Angular接口,由路由器调用。 CanActivate
的实现可以返回一个observable,一个promise或一个boolean。当它返回一个observable时,路由器会订阅它 - 它会看到对它内部组成的observable进行的订阅,并最终 - 对你在问题中包含的hasBookInApi
返回的可观察对象进行订阅。