2017-03-16 5 views
2

ブローコードは、私はHTTP要求を作成し、本がストアにすでにあるかどうかを確認するgoogleBooksサービスを呼び出していることを理解しngrx/example でbookexistルートガードからで起動します。私が理解できない部分は、ガードサービスのどこにでもsubscribeを呼んでいないということです。私の理解は、Anuglar2のhttp ObservablesはCold Observableとみなされ、誰かがそれを購読するまで呼び出されないということです。Rxjsは、どのように冷たい観測

質問:下記の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の実装は、観測可能な、約束またはブール値を返すことができます。観測可能なものを返すと、ルータはそのサブスクリプションに加入しています。サブスクリプションにはその中に構成されているオブザーバブルが表示され、最終的には質問に含まれているhasBookInApiによって返されたオブザーバブルになります。

関連する問題