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

问题描述 投票:24回答:4

我的模块.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()称为每次路线改变,我怎么能这样做?有谁可以帮助我。

angular typescript angular2-routing
4个回答
38
投票

你可以像这样从主要的activate调用router-outlet方法

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

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

Update -

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

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

3
投票

您可以订阅路由器的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;
                    }
                });
    }
}

2
投票

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

{ path: 'dashboard', component: DashboardComponent , canActivate: [AuthGuard] },

您的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;
  }
 }

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

app.module.ts:

......... Your code.......... 
import { AuthGuard } from './_guards/index';
..........Your code..............
  providers: [
    AuthGuard,
    ........
],

0
投票

你可以参考:NgRx Router

捕获ngrx效果中的所有“Go”操作以在路径更改之前执行操作,或者在此操作的reducer中捕获路径更改后调用函数。

© www.soinside.com 2019 - 2024. All rights reserved.