2016-09-06 95 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