How to detect a route change in Angular?

前端 未结 22 1540
花落未央
花落未央 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.

    0 讨论(0)
  • 2020-11-22 05:29

    Just make changes on AppRoutingModule like

    @NgModule({
    imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
      exports: [RouterModule]
    })
    
    0 讨论(0)
  • 2020-11-22 05:29

    Angular 8. Check whether the current route is the base route.

      baseroute: boolean;
      constructor(
        private router: Router,
      ) {
        router.events.subscribe((val: any) => {
          if (val.url == "/") {
            this.baseroute = true;
          } else {
            this.baseroute = false;
          }
        });
      }
    
    0 讨论(0)
  • 2020-11-22 05:31

    Angular 4.x and above :

    This can be achieved using url property of ActivatedRoute class as below,

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

    Note: That you need to import and inject the provider from angular/router package

    import { ActivatedRoute } from '@angular/router`
    

    and

    constructor(private activatedRoute : ActivatedRoute){  }
    
    0 讨论(0)
提交回复
热议问题