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

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


当前回答

我从RC 5开始这样做

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

其他回答

在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) 
    });
  }
}

这里的答案是正确的路由器弃用。对于最新版本的路由器:

this.router.changes.forEach(() => {
    // Do whatever in here
});

or

this.router.changes.subscribe(() => {
     // Do whatever in here
});

要了解两者之间的区别,请查看这个SO问题。

Edit

对于最新的您必须做:

this.router.events.subscribe(event: Event => {
    // Handle route change
});

如果您只是想检查路由/查询参数更改,如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
 }   
}

角4。X及以上:

这可以通过使用ActivatedRoute类的url属性来实现,如下所示:

this.activatedRoute.url.subscribe(url =>{
     console.log(url);
});

注意: 你需要从angular/router包中导入和注入提供商

import { ActivatedRoute } from '@angular/router`

and

constructor(private activatedRoute : ActivatedRoute){  }

在Angular 8中,你应该这样做。router.events。订阅((事件:事件)=> {})

例子:

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

@Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
})
export class AppComponent {

    constructor(private router: Router) {
        //Router subscriber
        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
                //do something on start activity
            }

            if (event instanceof NavigationError) {
                // Handle error
                console.error(event.error);
            }

            if (event instanceof NavigationEnd) {
                //do something on end activity
            }
        });
   }
}