Angular 4檢測路由變化,可使用router.events來監聽:html
支持的事件類型:this
在判斷事件類型須要導入對應的事件類型,如:code
import { Router, NavigationStart } from '@angular/router';
監聽單一事件router
this.router.events .filter((event) => event instanceof NavigationEnd) .subscribe((event:NavigationEnd) => { //do something });
監聽多個事件htm
constructor(router:Router) { router.events.subscribe(event:Event => { if(event instanceof NavigationStart) { // } else if(event instanceof NavigationEnd) { // } else if(event instanceof NavigationCancel) { // } else if(event instanceof NavigationError) { // } else if(event instanceof RoutesRecognized) { // } }); }
運用實例參考:http://www.javashuo.com/article/p-ytyoqxcu-dt.html