看個具體的例子:
在app.component.ts裡注入Router:
export class AppComponent {
constructor(router:Router){
console.log('Checking router');
router.events.pipe(
filter(e => e instanceof ActivationStart)
).subscribe(e =>{
console.log('路由開始了', e);
});
router.events.subscribe(e => {
console.log('all events: ', e);
});
}
}
events是個Observable,一旦其next方法被調用,我們使用subscribe注冊的回調就會被觸發。
首先的event名稱為:NavigationStart

注意:我的應用代碼裡,這個events Observable有兩個subscriber,分别羅列如下:
router.events兩次調用subscribe之後,它擁有了兩個Observables:
這裡,Router.js主動發起next調用,傳入的對象就是NavigationStart:
第二個事件是RoutesRecognized:
第三個事件:
GuardsCheckStart:
這裡依次fire餘下的事件:
function runCanActivateChecks(futureSnapshot, checks, moduleInjector, forwardEvent) {
return from(checks).pipe(concatMap((/**
* @param {?} check
* @return {?}
*/
(check) => {
return from([
fireChildActivationStart(check.route.parent, forwardEvent),
fireActivationStart(check.route, forwardEvent),
runCanActivateChild(futureSnapshot, check.path, moduleInjector),
runCanActivate(futureSnapshot, check.route, moduleInjector)
])
.pipe(concatAll(), first((/**
* @param {?} result
* @return {?}
*/
result => {
return result !== true;
}), (/** @type {?} */ (true))));
})), first((/**
* @param {?} result
* @return {?}
*/
result => {
return result !== true;
}), (/** @type {?} */ (true))));
}
all events: NavigationStart {id: 1, url: "/", navigationTrigger: "imperative", restoredState: null}
14:37:43.263 core.js:40855 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
14:39:51.283 app.component.ts:69 all events: RoutesRecognized {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}
14:40:33.209 app.component.ts:69 all events: GuardsCheckStart {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}
14:42:09.156 app.component.ts:69 all events: ChildActivationStart {snapshot: ActivatedRouteSnapshot}
14:42:09.161 app.component.ts:65 路由開始了 ActivationStart {snapshot: ActivatedRouteSnapshot}
14:42:12.720 app.component.ts:69 all events: ActivationStart {snapshot: ActivatedRouteSnapshot}
14:42:12.722 app.component.ts:69 all events: GuardsCheckEnd {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot, shouldActivate: true}
14:42:12.722 app.component.ts:69 all events: ResolveStart {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}
14:42:12.723 app.component.ts:69 all events: ResolveEnd {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}
14:42:12.726 (index):16 trying to create new tag: wild
14:42:12.729 (index):16 trying to create new tag: h1
14:42:12.731 app.component.ts:69 all events: ActivationEnd {snapshot: ActivatedRouteSnapshot}
14:42:12.732 app.component.ts:69 all events: ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
14:42:12.733 app.component.ts:69 all events: NavigationEnd {id: 1, url: "/", urlAfterRedirects: "/"}
14:42:12.734 app.component.ts:69 all events: Scroll {routerEvent: NavigationEnd, position: null, anchor: null}
14:42:13.372