2017-05-09 50 views

回答

0

可以使用ActivatedRouteSnapshotRouterStateSnapshot解決您的問題。

這裏是我的Angular2應用程序的代碼示例。

AUTH-guard.ts

import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 
import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { AuthCookie } from '../shared/services/auth-cookies-handler'; 

@Injectable() 
export default class AuthGuard implements CanActivate { 
    constructor(private router: Router, private _authCookie: AuthCookie) { } 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { 
     if (this._authCookie.getAuth()) { 
      //add your custom conditions for route nevigation 
      return true; 
     } 
     else { 
      this.router.navigate(['/login']); 
      return false; 
     } 
    } 
} 

app.routing.ts

import {ModuleWithProviders } from '@angular/core'; 
import {Routes, RouterModule } from '@angular/router'; 
import { HomeComponent } from '../home/home'; 
import {LoginComponent } from '../account/login'; 
import { RegisterComponent } from '../account/register'; 
import { JourneyComponent } from '../journey/journey.component'; 
import AuthGuard from './auth-guard'; 

const appRoutes: Routes = [ 
    { 
     path: '', 
     redirectTo: 'home', 
     pathMatch: 'full' 
    }, { 
     path: 'journey', 
     component: JourneyComponent, 
     children: [ 
      { path: '', redirectTo: 'details', pathMatch: 'full' }, 
      { path: 'details', component: JourneyDetailsComponent, canActivate: [AuthGuard] }, 
      { path: 'documents', component: DocumentsComponent, canActivate: [AuthGuard] }, 
      { path: 'review', component: ReviewComponent, canActivate: [AuthGuard] }, 
      { path: 'payment', component: PaymentComponent, canActivate: [AuthGuard] } 
     ] 
     , canActivate: [AuthGuard] 
    }, 
    { 
     path: 'application', 
     component: ApplicationComponent, 
     canActivate: [AuthGuard] 
    }, 
    { 
     path: 'login', 
     component: LoginComponent 
    }, 
    { 
     path: 'activate-account/:uid', 
     component: AccountComponent 
    }, 
    { 
     path: 'reset-password/:uid', 
     component: ResetPasswordComponent 
    }, 
    { 
     path: 'home', 
     component: HomeComponent 
    }, 
    { 
     path: 'register', 
     component: RegisterComponent 
    } 
]; 

export const appRoutingProviders: any[] = [ 
]; 

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); 

希望這將幫助你!