【发布时间】:2016-12-09 13:10:49
【问题描述】:
我正在尝试创建路由保护,阅读了一些博客和Angular 2 official documentation。但我仍然无法让它工作。
这里是 RouteGuard(我已经删除了日志记录逻辑以确保问题出在路由中,而不是在身份验证逻辑中。):
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Router, CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class RouteGuard implements CanActivate {
constructor() {
var a = 5;
console.log("RouterGuard called");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log("RouterGuard called");
return true;
}
}
这里我有一些路线:
import { RouteGuard } from './common/routeGuard';
import { ClassifiersComponent } from './components/classifiers/classifiers.component';
import { Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'classifiers', component: ClassifiersComponent, canActivate: [RouteGuard] },
];
然后我在引导程序方法中传递它们:
import { RouteGuard } from './app/common/routeGuard';
import { ClassifiersComponent } from './app/components/classifiers/classifiers.component';
import { HomeComponent } from './app/components/home/home.component';
import { routes } from './app/app.routes';
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
providers: [
{ provide: LocationStrategy, useClass: PathLocationStrategy },
{ provide: APP_BASE_HREF, useValue: '/' },
RouteGuard
],
declarations: [
AppComponent,
HomeComponent,
ClassifiersComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}
我不确定这一切有什么问题,可能是我遗漏了一些重要的东西。从调试中我可以看出它正在命中 canActivate() 断点,但不执行 console.log,构造函数也是如此。
编辑: 其他没有任何路由认证的路由都可以正常工作。
EDIT2: 我正在使用 角度/核心2.2.0, 角度/路由器 3.2.0
【问题讨论】:
-
当前行为是什么?预期的行为是什么?
-
目前阻塞路由?我不确定,因为它没有在控制台中写入任何内容。应该写的是调用RouteGuard。并且 rout 不应该被阻塞,因为 canActivate() 总是返回 true;
-
那么
RouterGuard called没有被打印到浏览器控制台? -
{ path: '', component: HomeComponent },应该是{ path: '', component: HomeComponent, pathMatch: 'full' },如果空路径路由没有子路由。 -
不知道。你能在 Plunker 中复制吗? Plunker 有一个 Angular2 TS 模板
标签: angular typescript angular2-routing