2016-09-06 96 views
0

我一直在嘗試實施身份驗證後衛幾天,但我仍然無法讓我的canActivate函數運行。我的認證後衛看起來像這樣(這顯然是不實際守着什麼):帶登錄後衛的角度2路由器

import { Injectable } from 'angular2/core'; 
import { Observable } from "rxjs/Rx"; 

@Injectable() 
export class LoggedInGuard implements CanActivate { 
    constructor() {} 

    canActivate():Observable<boolean>|boolean { 
    console.log('AuthGuard#canActivate called'); 
    return true; 
    } 
} 

而且我的應用程序組件,它進口保護,並實現了路由器的樣子:

import { Component } from 'angular2/core'; 
import { HTTP_PROVIDERS } from 'angular2/http'; 
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; 
import 'rxjs/Rx'; // load the full rxjs 

import { CharacterListComponent } from './characters/character-list.component'; 
import { VehicleListComponent } from './vehicles/vehicle-list.component'; 


import { LoggedInGuard } from './login.guard.ts' 

@Component({ 
    selector: 'story-app', 
    templateUrl: 'app/app.component.html', 
    directives: [ROUTER_DIRECTIVES], 
    providers: [ 
    HTTP_PROVIDERS, 
    ROUTER_PROVIDERS, 
    LoggedInGuard 
    ] 
}) 
@RouteConfig([ 
    { path: '/characters', name: 'Characters', component: CharacterListComponent, useAsDefault: true }, 
    { path: '/vehicles', name: 'Vehicles', component: VehicleListComponent, canActivate: [LoggedInGuard] } 
    ]) 
export class AppComponent { } 

每次LoggedInGuard在運行canActivate函數時,應該創建一個日誌條目。在鏈接之間導航時,永遠不會創建日誌條目,這意味着該功能永遠不會運行。您可以看到Plunker採取行動here

任何有識之士將不勝感激。我敢肯定,這將是一個容易的人比較熟悉的角2

+0

嘿,我也有同樣的問題,你有沒有找到任何解決方案,請分享 – Sujithrao

+0

@Sujithrao您正在運行Angular 2的哪個版本?這裏有大量的發佈,你可以找到許多文檔(以博客文章,YouTube視頻和SO問題的形式)。確保你使用的是Angular 2.xx(而不是發佈候選版本),不要試圖在2016年9月15日之前實現示例,並嘗試使用[官方角度文檔](https://angular.io/docs/ts/latest /) – dslosky

回答

1

您正在使用的方式老版的角2,請嘗試升級您的應用程序到RC6如果可能的話,

,你可以看看到新的引用,

Routing & Navigation

而且角度團隊已經創建Plunker展示的概念。包括認證後衛。

希望這有助於!

+0

糟糕!我一直在本地使用2.0.0-beta.17(我很確定它是RC6,對吧?),並且我已經更新了Plunker來做同樣的事情。我還簡化了我的Plunker示例,並將更新我的原始問題以反映這一點。我的問題仍然存在,我將非常感謝您提供更多見解 – dslosky

+0

不是[2.0.0-beta.17](https://github.com/angular/angular/blob/master/CHANGELOG.md#200 -beta17-2016-04-28)已經過時了,現在的版本是RC6,請檢查我在關於如何設置相同的答案中添加了Plunker。 –

+0

哦,哇,感謝那個鏈接......我之前和那個Plunker一起工作過,而且非常有幫助!我無法在我的項目中使用Node和npm,所以我的實現必須有所不同,但我會升級到RC6,如果一切順利,您將得到答案:) – dslosky