2016-09-25 130 views
0

我開始學習有關angular 2的所有信息,並且目前遇到問題。angular2 - 檢查用戶登錄

const appRoutes: Routes = [ 
    {path: 'start', 
    component: StartComponent, 
    children:[{path: '' }, 
     { 
     path:'nested', component:NestedTestComponent 
     } 
    ]}, 
    {path: '', component:LoginFormComponent} 
]; 

有「基地」的路徑,顯示登錄表單,用戶輸入憑據後(他們是正確的),用戶將被引導到「啓動」:我在我的應用程序定義了這些途徑並將其作爲「嵌套」嵌套路線。 這很好。但我想以某種方式限制用戶訪問「開始」和「嵌套」,如果用戶沒有登錄。因爲這是目前可能的只是作爲一個URL輸入。

我的index.html是這樣的:

<body> 
    <app-root>Loading...</app-root> 
</body> 

app.component:

@Component({ 
    selector: "app-root", 
    template: ` 
     <router-outlet></router-outlet> 
     `, 
    styleUrls: ['./app.component.css'] 
}) 

start.component

<nav> 
    <div class="nav-wrapper"> 
     <a href="#" class="brand-logo center"></a> 
     <ul id="nav-mobile" class="right hide-on-med-and-down"> 
     <li><a (click)="logout()">Logout</a></li> 
     </ul> 
    </div> 
    </nav> 
    <router-outlet></router-outlet> 

由於一切都以某種方式嵌套在我的方法是檢查app.component是否用戶使用此登錄:

export class AppComponent { 



    constructor(af:AngularFire, router:Router){ 
    if(af.auth.getAuth() == null){ 
     //redirect to start 
     console.log('redirect to login'); 
     router.navigate(['']); 
    }else{ 
     console.log('not redirect to login'); 
    } 
    } 
} 

這可以正常檢測用戶是否應該重定向。但是,router.navigate(['']);不起作用。它什麼都不做。

回答

3

使用CanActivate,您可以允許用戶只有在路由中激活或重定向登錄時才訪問頁面。

import { ModuleWithProviders } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
import { CanActivateAuthGuard } from './auth.service' 

import { MyComponent } from './app.component'; 

const routes: Routes = [ 
    { path: '/home', component: MyComponent , canActivate: [CanActivateAuthGuard]}] 

/在身份驗證服務/

import { CanActivate, Router } from '@angular/router'; 

@Injectable() 
export class CanActivateAuthGuard implements CanActivate { 
    constructor(private router: Router) {} 
    if (this.authService.isLoggedIn()) { 
     return true; 
    } 
    //Redirect the user before denying them access to this route 
    this.router.navigate(['/login']); 
    return false; 
} 
+0

你能否提供一個例子*在回答*?鏈接本身是[無用](http://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer )。 – jonrsharpe

+0

從'@ angular/core'導入{ModuleWithProviders}; 從'@ angular/router'導入{Routes,RouterModule}; 從'./auth.service'導入{CanActivateAuthGuard} 從'./app.component'導入{MyComponent}; 常量路線:路線= [ {路徑: '/家',組成:MyComponent的,canActivate:[CanActivateAuthGuard]}] /*在身份驗證服務*/ – Manish

+0

請編輯**到答案**。 – jonrsharpe