我正在升级到angular 5我的项目,我无法理解激活如何不再起作用:
//package.json:
dependencies": {
"@angular/animations": "~5.1.3",
"@angular/cdk": "5.0.3",
"@angular/common": "~5.1.3",
"@angular/compiler": "~5.1.3",
"@angular/core": "~5.1.3",
"@angular/flex-layout": "2.0.0-beta.12",
"@angular/forms": "~5.1.3",
"@angular/http": "~5.1.3",
"@angular/material": "5.0.3",
"@angular/platform-browser": "~5.1.3",
"@angular/platform-browser-dynamic": "~5.1.3",
"@angular/router": "~5.1.3",
"@ngx-translate/core": "^9.0.2",
"amazon-cognito-identity-js": "^1.25.0",
"angular-in-memory-web-api": "^0.5.2",
"angular2-highcharts": "^0.5.5",
"core-js": "^2.4.1",
"highcharts-export-csv": "git+https://github.com/highcharts/export-csv.git",
"leaflet": "^1.2.0",
"leaflet-draw": "^0.4.12",
"leaflet.markercluster": "^1.1.0",
"ng2-dnd": "^4.2.0",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},
我的路由和模块文件:
//app.routing
const APP_ROUTES: Routes = [
{
path: '',
canActivate: [LoggedInGuard],
children: [
{path: '', loadChildren: 'app/myModule/myModule.module#MyModule', pathMatch: 'full'}
]
},
{path: '**', redirectTo: ''}
];
//app.module
providers: [
LoggedInGuard
],
和myModule中的路由文件:
myModule.routing
const MYMODULE_ROUTES: Routes = [
{path: '', component: MyModuleComponent},
];
问题是永远不会调用LoggedInGuard,我无法理解我缺少什么
我添加了我的loggedInGuard函数,因为@Rowel de Guzman评论
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private router: Router, private userService: UserService) {
console.log("constructor");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log("inside canActivate!");
if (state.url !== '/login') {
this.router.navigate(['/login']);
return false;
}
return true;
} }
答案 0 :(得分:1)
{
path: '',
canActivate: [LoggedInGuard],
children: [
{path: '', loadChildren: 'app/myModule/myModule.module#MyModule', pathMatch: 'full'}
]
}
这只保护一条路线。你应该改用它:
{
path: '',
canActivateChild: [LoggedInGuard],
children: [
{path: '', loadChildren: 'app/myModule/myModule.module#MyModule', pathMatch: 'full'}
]
}
这将保护每个儿童路线,而不仅仅是父母。
答案 1 :(得分:0)
我发现它,问题出在myModule.routing中,我写的是完整的路线而不是亲戚,因为它没有激活它所传递的保护。
谢谢你的时间!
答案 2 :(得分:0)
它与角度5一起使用。 示例:
import {AuthGuard} from'/services/authguard.service.ts';
{
path: '/myPath',
canActivate: [AuthGuard],
component:myComponent,
data:{}
}