How to detect a route change in Angular?

前端 未结 22 1974
花落未央
花落未央 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:28

    I am working with angular5 application and i'm facing the same issue . when i go through Angular Documentation they provide best solution for handling router events.check following documentation.

    • Router Events in Angular Route events in angular5

    • But specifically for the case provide in question we need NavigationEnd Event

      Navigation End Event Angular

    Represents an event triggered when a navigation ends successfully

    How to use this ?

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRouteSnapshot, NavigationEnd } from '@angular/router';
    @Component({
        selector: 'app-navbar',
        templateUrl: './navbar.component.html',
        styleUrls: ['./navbar.component.css']
    })
    export class NavbarComponent implements OnInit {
        constructor(private router: Router) { }
        ngOnInit(): void {
            //calls this method when navigation ends
            this.router.events.subscribe(event => {
                if (event instanceof NavigationEnd) {
                    //calls this stuff when navigation ends
                    console.log("Event generated");
                }
            });
        }
    }
    

    When to use this ?

    In my case my application share common dashboard for all users such as users , Admins , but i need to show and hides some navbar options as per user types.

    That's why whenever url changes i need to call service method which returns logged in user information as per response i will go for further operations.

提交回复
热议问题