【问题标题】:How to call a function on every route change in angular2如何在angular2中的每条路线更改上调用一个函数
【发布时间】:2017-07-16 03:43:40
【问题描述】:

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


【解决方案1】:

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

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

每次路由改变时都会调用。

更新 -

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

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

【讨论】:

  • 嗨,pradeep,它工作得很好,但是当我点击浏览器中的后退按钮时它没有被调用。
  • 到目前为止我还没有测试过,所以不能说什么
  • 好的,但你的回答对我帮助很大。谢谢。
  • 嗨,Pradeep,你能回答我的问题吗?
  • 它也适用于浏览器后退按钮。我在 chrome、mozilla 和 IE @Daniel 中对此进行了测试
【解决方案2】:

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

【讨论】:

  • filter 方法依赖于rxjs。简单地说,import 'rxjs/add/operator/filter'; 在您的 TS 文件开头添加此导入,应该可以正常工作。
【解决方案3】:

你可以像下面这样在路由中调用指令:

{ 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,
    ........
],

【讨论】:

    【解决方案4】:

    您可以参考:NgRx Router

    在 ngrx 效果中捕获所有 'Go' 动作以在 路由更改之前执行操作,或者在此动作的 reducer 中调用函数在 路由更改之后.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多