如何在Angular2中在每个路由变化时调用一个函数。
如何在Angular2中在每个路由变化时调用一个函数。
我的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文件,
export class Mainapp { showBeforeLogin:any = true; showAfterLogin:any; constructor( public router: Router) { this.changeOfRoutes(); } changeOfRoutes(){ if(this.router.url === '/'){ this.showAfterLogin = true; } } }
我想在每一次路由变化时调用changeofRoutes()函数,我应该怎么做?能否有人帮忙解决。
admin 更改状态以发布 2023年5月20日
你可以订阅路由器的NavigationEnd
事件,并使用urlAfterRedirects
方法检索URL。
-
我强烈建议你使用
urlAfterRedirects
,因为似乎你需要在条件下使用showAfterLogin
。 -
假设你正在将
/test-page
重定向到/
,并依赖于router.url
。在这种情况下,应用程序已经被重定向到/
,但router.url
将返回/test-page
,这里就会出现问题('/test-page' != '/'
)。
简单地在你的构造函数中进行以下更改:
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; } }); } }
你可以像这样从主router-outlet
中调用activate
方法:
每次路由更改时都会调用它。
更新 -
另一种实现相同效果的方法是订阅路由事件,甚至可以根据导航状态过滤它们,例如开始和结束,例如:
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 */} }); }