How to detect a route change in Angular?

前端 未结 22 1589
花落未央
花落未央 2020-11-22 04:40

I am looking to detect a route change in my AppComponent.

Thereafter I will check the global user token to see if he is logged in. Then I can redirect t

22条回答
  •  梦毁少年i
    2020-11-22 05:08

    RxJS 6

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

    Thanks to Peilonrayz (see comments below)

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

    You can also filter by the given event:

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

    Using the pairwise operator to get the previous and current event also is an nice idea. https://github.com/angular/angular/issues/11268#issuecomment-244601977

    import 'rxjs/add/operator/pairwise';
    import { Router } from '@angular/router;
    
    export class AppComponent {
        constructor(private router: Router) {
            this.router.events.pairwise().subscribe((event) => {
                console.log(event);
            });
        };
    }
    

提交回复
热议问题