1

我正在将我的项目升级到 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;

} }

4

3 回答 3

3
{
    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'}
    ]
}

这将保护每个子路由,而不仅仅是父路由。

于 2018-01-15T08:32:24.880 回答
1

我找到了,问题出在 myModule.routing 中,我写的是完整的路由而不是亲戚,因为它没有 canActivate 保护,所以它通过了。

谢谢你的时间!

于 2018-01-16T07:59:10.337 回答
0

它适用于角度 5。示例:

import {AuthGuard} from'/services/authguard.service.ts';

{
    path: '/myPath',
    canActivate: [AuthGuard],
    component:myComponent,
    data:{}

}
于 2018-09-03T15:39:39.757 回答