我正在寻找在我的AppComponent中检测路由变化。

然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。


当前回答

我是这么说的:

class ClassName {
  constructor(private router: Router) {
    router.events.subscribe((value) => {
        // see this 
        console.log(value instanceof NavigationEnd) 
    });
  }
}

其他回答

在Angular 2中,你可以订阅(Rx事件)一个Router实例。 你可以这样做

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*whatever*/)
  }
}

编辑(从rc.1开始)

class MyClass {
  constructor(private router: Router) {
    router.changes.subscribe((val) => /*whatever*/)
  }
}

编辑2(从2.0.0开始)

请参见:路由器。活动文档

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

在花了一些时间寻找解决方案后,我找到了Angular 13.1.1的两个更新的变通方案:

第一选择:

  constructor(private router: Router) {
    router.events.forEach((event) => {
      if (event instanceof NavigationStart) {
        // Your code
        // Use (event.url) to get URL that is being navigated
      }
    });
  }

第二个选项

routerSubscription:订阅| undefined; 构造函数(私有路由器:router) {} ngAfterViewInit(): void { 这一点。routerSubscription = this.router.events.subscribe((event) => { if(事件实例of NavigationEnd) { //你的代码 //使用(event.url)获取正在导航的URL } }); }

记得取消订阅销毁循环

 ngOnDestroy(): void {
    this.routerSubscription?.unsubscribe();
  }

还要根据您的情况注意是否更好地使用

事件实例的NavigationStart

or

事件实例的NavigationEnd

如果您只是想检查路由/查询参数更改,如localhost:4200/users/1?编辑=1到localhost:4200/users/2?Edit =0你可以像下面这样使用可观察的参数。

import { ActivatedRoute, Params } from '@angular/router';
export class SomeClass implements OnInit {

paramFromRoute;

constructor(private route: ActivatedRoute) { }

ngOnInit() {
  this.paramFromRoute = this.route.snapshot.params['paramName']; // this one is required for getting it first time

  this.route.params.subscribe((params:Params)=>{
    this.paramFromRoute =  params['paramName'] // whenever route is changed, this function will triggered.
  });
  // for queryParams you can subscribe to this.route.queryParams
 }   
}

为那些使用Angular9+的人更新了答案,通过使用@angular/ Router提供的路由器API并监听路由变化

import { Component } from '@angular/core';
import { Router,NavigationEnd  } from '@angular/router';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      
      name = 'Get Current Url Route Demo';
      currentRoute: string;
     routeSubscription: subscription;
    
      constructor(private router: Router){
        console.log(router.url);
        
        this.routeSubscription = router.events.filter(event => event instanceof NavigationEnd)
              .subscribe(event => 
               {
                  this.currentRoute = event.url;          
                  console.log(event);
               });
        }
    }

我会这样写:

ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
  .subscribe(() => {
  } );
}

ngOnDestroy() {
this.routed.unsubscribe();
}