如何在angular2的每条路线更改上调用函数 [英] How to call a function on every route change in angular2

查看:71
本文介绍了如何在angular2的每条路线更改上调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的module.ts,

My module.ts,

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule,Router }   from '@angular/router';
import { AppComponent }  from './crud/app.component';
import { Profile }  from './profile/profile';
import { Mainapp }  from './demo.app';
import { Navbar }  from './header/header';
// import {ToasterModule, ToasterService} from 'angular2-toaster';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({

  imports:      [ BrowserModule,FormsModule, ReactiveFormsModule ,
  RouterModule.forRoot([
      { path: '', component:AppComponent},
      { path: 'login', component:AppComponent},
      { path: 'profile', component:Profile}
    ]) ],
  declarations: [ AppComponent,Mainapp,Navbar,Profile ],
  bootstrap:    [ Mainapp ]
})
export class AppModule { 

}

在这里,我想在每次更改路线时从main.ts调用一个函数,该怎么做.任何人都可以帮助我.谢谢. 我的mainapp.ts,

Here i want to call a function from main.ts on every route change and how can i do that.Can anyone please help me.Thanks. My mainapp.ts,

    export class Mainapp {

    showBeforeLogin:any = true;
    showAfterLogin:any;
    constructor( public router: Router) {
     this.changeOfRoutes();

     }
     changeOfRoutes(){
      if(this.router.url === '/'){
         this.showAfterLogin = true;
      }
     }
}

我想在每次路线更改时都调用此changeofRoutes(),我该怎么办?有人可以帮助我吗.

I want to call this changeofRoutes() for every route change and how can i do that?Can anyone please help me.

推荐答案

您可以像这样从主router-outlet调用activate方法

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

<router-outlet  (activate)="changeOfRoutes()"></router-outlet>

每当路线更改时都会调用.

which will call every time when route will change.

另一种实现此目的的方法是订阅路由器事件,即使您可以根据导航状态将它们过滤掉也可能是开始和结束,例如-

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

这篇关于如何在angular2的每条路线更改上调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆