How to detect a route change in Angular?

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

    Capture route change events in the following manner...

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

提交回复
热议问题