我一直在嘗試實施身份驗證後衛幾天,但我仍然無法讓我的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
嘿,我也有同樣的問題,你有沒有找到任何解決方案,請分享 – Sujithrao
@Sujithrao您正在運行Angular 2的哪個版本?這裏有大量的發佈,你可以找到許多文檔(以博客文章,YouTube視頻和SO問題的形式)。確保你使用的是Angular 2.xx(而不是發佈候選版本),不要試圖在2016年9月15日之前實現示例,並嘗試使用[官方角度文檔](https://angular.io/docs/ts/latest /) – dslosky