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

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


当前回答

只需在AppRoutingModule上进行更改

@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
  exports: [RouterModule]
})

其他回答

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

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

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

在花了一些时间寻找解决方案后,我找到了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

Angular 7,如果你想订阅路由器

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

import { filter } from 'rxjs/operators';

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationEnd)  
  ).subscribe((event: NavigationEnd) => {
    console.log(event.url);
  });
}

@Ludohen的回答很好,但如果你不想使用instanceof,请使用下面的方法

this.router.events.subscribe(event => {
  if(event.constructor.name === "NavigationStart") {
    // do something...
  }
});

通过这种方式,您可以检查当前事件名称作为字符串,如果事件发生,您可以执行您计划的函数要执行的操作。