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

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


当前回答

为那些使用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);
               });
        }
    }

其他回答

以以下方式捕获路由更改事件…

import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';

@Component({
    selector: "my-app",
    templateUrl: "app/app.component.html",
    styleUrls: ["app/app.component.css"]
})
export class AppComponent {

    constructor(private cacheComponentObj: CacheComponent,
        private router: Router) {

        /*  Route event types
            NavigationEnd
            NavigationCancel
            NavigationError
            RoutesRecognized
        */
        router.events.forEach((event: NavigationEvent) => {

            //Before Navigation
            if (event instanceof NavigationStart) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }

            //After Navigation
            if (event instanceof NavigationEnd) {
                switch (event.url) {
                case "/app/home":
                {
                    //Do Work
                    break;
                }
                case "/app/About":
                {
                    //Do Work
                    break;
                }
                }
            }
        });
    }
}

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

我从RC 5开始这样做

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

RxJS 6

router.events.pipe(filter(event => event instanceof NavigationStart))

感谢Peilonrayz(见下面的评论)

new router >= RC.3

import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router';

constructor(router:Router) {
  router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

你也可以通过给定的事件进行过滤:

import 'rxjs/add/operator/filter';

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:NavigationStart) => {
      // You only receive NavigationStart events
    });
}

使用成对操作符来获取先前和当前事件也是一个不错的想法。https://github.com/angular/angular/issues/11268#issuecomment-244601977

进口的rxjs /添加/运营商/成对的; import {Router} from '@angular/ Router '; 导出类AppComponent { 构造函数(私有路由器:router) { This.router.events.pairwise ().subscribe((event) => { console.log(事件); }); }; }

角4。X及以上:

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

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

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

import { ActivatedRoute } from '@angular/router`

and

constructor(private activatedRoute : ActivatedRoute){  }