angular路由事件

Angular 4檢測路由變化,可使用router.events來監聽:html

支持的事件類型:this

  • NavigationStart:導航開始
  • NavigationEnd:導航結束
  • NavigationCancel:取消導航
  • NavigationError:導航出錯
  • RoutesRecoginzed:路由已認證

在判斷事件類型須要導入對應的事件類型,如: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
相關文章
相關標籤/搜索