How to detect a route change in Angular?

前端 未结 22 2029
花落未央
花落未央 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条回答
  •  不要未来只要你来
    2020-11-22 05:11

    above most of solutions correct , but i am facing issue this emit multiple times 'Navigation emit' event.when i was change any route this event is triggered. So hear is the complete solution for Angular 6.

    import { Subscription } from 'rxjs/Subscription';
    import 'rxjs/add/operator/do';
    import 'rxjs/add/operator/filter';    
    
    export class FooComponent implements OnInit, OnDestroy {
       private _routerSub = Subscription.EMPTY;
       constructor(private router: Router){}
    
       ngOnInit(){
         this._routerSub = this.router.events
          .filter(event => event instanceof NavigationEnd)
          .subscribe((value) => {
             //do something with the value
         });
      }
    
      ngOnDestroy(){
       this._routerSub.unsubscribe();
      }
    } 
    

提交回复
热议问题