Angular获取当前激活路由与监听路由

Angualr获取当前激活路由可以通过PlatformLocationRouter获取,还有一说Location也可以,看名字估计是没问题的。这里就写前面两个,PlatformLocation这个包来自@angular/commonRouter来自@angular/router

constructor(
    private route:Router,
    private planform: PlatformLocation
  ) { }

  routerPath:string="";
  ngOnInit() {
  	//去掉路由前面的'/'
    console.log("PlatformLocation方式:",this.planform.pathname.substr(1));

	//同时具有监听的功能
    this.route.events.subscribe((data)=>{
      //data返回一堆路由事件,所有得筛选自己需要的,这里选择路由导航结束之后
      if(data instanceof NavigationEnd){
        this.routerPath=data.url.substr(1);
        console.log("Router方式:",this.routerPath);
      }
    })
  }

结果:
Angular获取当前激活路由与监听路由_第1张图片
两种方式都能获取到当前激活的路由名称,但是相对而言使用Router会比较好,因为Router能够实时的监听路由的变化,一旦路由发生了变化能马上监听到,在上面的代码中events事件订阅之后会返回对个不同的路由导航事件,这里需要根据自己的需要进行选择,关于路由导航事件,官网里都有介绍,参见这里的路由事件部分

其实ActivatedRoute也可以获取,但是实际使用的时候要么繁琐要么为空,不推荐

你可能感兴趣的:(Angular)