2017-03-16 60 views
2

吹碼是來自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); 
    }); 
} 

回答

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是角界面,它是由路由器調用。 CanActivate的實現可以返回一個observable,一個promise或一個boolean。當它返回一個可觀察對象時,路由器會訂閱它 - 它看到了對它構成的觀察值的訂閱,並且最終 - 到您在問題中包含的hasBookInApi返回的可觀察值。