最近在項(xiàng)目中,有個(gè)需求:需要監(jiān)控路由變化實(shí)現(xiàn)某個(gè)功能,所以研究了一番官網(wǎng)和路由相關(guān)的api
router.events()是一個(gè)observable對象,我們可以通過訂閱它來獲取路由變化的相關(guān)信息
- NavigationStart
- RouteConfigLoadStart
- RouteConfigLoadEnd
- RoutesRecognized
- GuardsCheckStart
- ChildActivationStart
- GuardsCheckEnd
- ResolveStart
- ResolveEnd
- ChildActivationEnd
- NavigationEnd
- NavigationCancel
- NavigationError
evnets提供了以上諸多類型的事件,方便我們根據(jù)事件的類型進(jìn)行過濾(關(guān)于rxjs的過濾操作就不再介紹)
constructor(private ref: ChangeDetectorRef, private router: Router) {
}
ngOnInit() {
this.routerEventsListener = this.router.events
.filter(event => event instanceof NavigationEnd) //根據(jù)事件的類型進(jìn)行過濾
.subscribe((event) => {
// your operation
this.ref.detectChanges(); //我的操作
});
}
大家一定要注意保護(hù)自己的操作,因?yàn)閞outer.events是全局的,所以在組件內(nèi)使用時(shí),最好在ngOndestory()中unsubscribe,筆者進(jìn)行了手動(dòng)觸發(fā)變更檢測的操作,導(dǎo)致在其他頁面路由跳轉(zhuǎn)時(shí),直接掛掉,原因是this.router.events所在組件此時(shí)已經(jīng)被銷毀,自然也就無法觸發(fā)組件的模板更新。
ngOnDestroy() {
this.routerEventsListener.unsubscribe();
}