How to call a function on every route change in angular2

前端 未结 4 744
清歌不尽
清歌不尽 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:09

    you can call activate method from main router-outlet like this

    
    

    which will call every time when route will change.

    Update -

    Another way to achieve the same is to subscribe to the router events even you can filter them out on the basis of navigation state may be start and end or so, for example -

    import { Router, NavigationEnd } from '@angular/router';
      
      @Component({...})
      constructor(private router: Router) {
        this.router.events.subscribe((ev) => {
          if (ev instanceof NavigationEnd) { /* Your code goes here on every router change */}
        });
      }
    

提交回复
热议问题