2017-05-26 35 views
0

我試圖根據角度的文檔登錄後工作得到重定向。 https://angular.io/docs/ts/latest/guide/router.html#!#teach-authguard-to-authenticateAngular 2 RouterStateSnapshot無法返回正確的網址

雖然有些文件名是不同的,但我基本上得到了相同的設置。

問題是,當我在authGuard, 中登錄RouterStateSnapshot url時,它始終會輸出第一條來自app-routing.module.ts('/ countries')的路線,而不是例如。 /國家/法國/ 34

authGuard

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    let url = state.url; 
    console.log(state); // always outputs first route from app-routing.module.ts ('/countries') 
    return this.checkLogin(url); 
} 

checkLogin(url: string): boolean { 
    if (this.userService.isLoggedIn()) { 
     return true; 
    } 
    this.userService.redirectUrl = url; 
    console.log(this.userService.redirectUrl); 

    // not logged in so redirect to login page 
    this.router.navigate(['/login']); 
    return false; 
} 

應用路由模塊

const routes: Routes = [ 
    { path: '', redirectTo: 'countries', pathMatch: 'full', canActivate: [AuthGuard]}, 
    { path: 'login', loadChildren: './authentication/authentication.module#AuthenticationModule' }, 
    { path: 'countries', loadChildren: './countries/countries.module#CountriesModule'}, 
    ... 
]; 

國家路由模塊

const routes: Routes = [ 
    { path: '', component: CountriesComponent, canActivate: [AuthGuard] }, 
    { path: ':name/:id', component: CountryComponent, canActivate: [AuthGuard] } 
]; 

希望有人能幫助

回答

1

您正在使用相同AuthGuard所有路徑,因此你看到了這個結果,你可以爲不同的路由創建不同的認證守衛,或者有一些邏輯來確定何時調用相同的canActivate

希望這有助於!