angular路由事件

Angular 4检测路由变化,可以使用router.events来监听:

支持的事件类型:

  • NavigationStart:导航开始
  • NavigationEnd:导航结束
  • NavigationCancel:取消导航
  • NavigationError:导航出错
  • RoutesRecoginzed:路由已认证

在判断事件类型需要导入对应的事件类型,如:

import { Router, NavigationStart } from '@angular/router';

监听单一事件

this.router.events
  .filter((event) => event instanceof NavigationEnd)
  .subscribe((event:NavigationEnd) => {
    //do something
});

监听多个事件

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) {
      //
    }
  });
}

运用实例参考:https://www.cnblogs.com/mary-123/p/10728614.html

原文地址:https://www.cnblogs.com/mary-123/p/11276454.html