我一直在尝试实施身份验证后卫几天,但我仍然无法让我的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