How to call a function on every route change in angular2

前端 未结 4 669
清歌不尽
清歌不尽 2021-02-01 02:50

My module.ts,

import { NgModule }      from \'@angular/core\';
import { BrowserModule } from \'@angular/platform-browser\';
import { RouterModule,Router }   from         


        
4条回答
  •  一个人的身影
    2021-02-01 03:19

    You can subscribe to the NavigationEnd event of router, and retrieve the URL with urlAfterRedirects method.

    • I strongly recommend you to use the urlAfterRedirects, because it seems that you need to showAfterLogin conditionally.

    • Let's say, you're redirecting /test-page to /; and you rely on router.url. In that case the app will already be redirected to / but router.url would return /test-page and here the issue comes ('/test-page' != '/').

    Simply, make the following changes in your constructor:

    export class Mainapp {
        showBeforeLogin:any = true;
        showAfterLogin:any;
    
        constructor(public router: Router) {
            this.changeOfRoutes();
    
            this.router.events
                .filter(event => (event instanceof NavigationEnd))
                    .subscribe((routeData: any) => {
                        if(routeData.urlAfterRedirects === '/') {
                            this.showAfterLogin = true;
                        }
                    });
        }
    }
    

提交回复
热议问题