如何在angular2中的每个路径变化上调用一个函数

Dan*_*iel 28 typescript angular2-routing angular

我的模块.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 { 

}
Run Code Online (Sandbox Code Playgroud)

在这里,我想从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;
      }
     }
}
Run Code Online (Sandbox Code Playgroud)

我想把这个changeofRoutes()称为每次路线改变,我怎么能这样做?有谁可以帮助我.

Par*_*ain 46

你可以像这样activate从main 调用方法router-outlet

<router-outlet  (activate)="changeOfRoutes()"></router-outlet>
Run Code Online (Sandbox Code Playgroud)

每次路线改变时都会打电话

  • 嗨pradeep,它工作得很好但是当我点击浏览器中的后退按钮时它没有被调用. (2认同)
  • 它也适用于浏览器后退按钮。我已经在 chrome、mozilla 和 IE @Daniel 中测试过了 (2认同)

Bur*_*sci 6

您可以订阅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;
                    }
                });
    }
}
Run Code Online (Sandbox Code Playgroud)


gau*_*ini 5

您可以在 Routes 中调用指令,如下所示:

{ path: 'dashboard', component: DashboardComponent , canActivate: [AuthGuard] },
Run Code Online (Sandbox Code Playgroud)

您的 AuthGuard 组件如下所示:

auth.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, 
RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
{
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/home'], { queryParams: { returnUrl: 
 state.url }});
    return false;
  }
 }
Run Code Online (Sandbox Code Playgroud)

你应该在 app.module.ts 文件中导入 AuthGuard 组件,并且应该在提供者中提供:

app.module.ts:

......... Your code.......... 
import { AuthGuard } from './_guards/index';
..........Your code..............
  providers: [
    AuthGuard,
    ........
],
Run Code Online (Sandbox Code Playgroud)