我正在进行简单的登录过程,我尝试保护某些路径,除非他们经过身份验证。
app.routing.ts
const appRoutes: Routes = [
{
path: 'add-merchant-admin',
component : AddMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'list-merchant-admin',
component : ListMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'login',
component : LoginComponent
},
{
path: '**',
component: NotFoundComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
authGard.service.ts
import { Injectable } from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {AuthenticationService} from "../authentication-service/authentication.service";
@Injectable()
export class AuthGard implements CanActivate {
constructor(private _authService:AuthenticationService, private _router:Router) { }
canActivate() {
if(this._authService.isLoggedIn)
return true;
this._router.navigate(['login']);
return false;
}
}
认证服务
@Injectable()
export class AuthenticationService {
isLoggedIn = false;
constructor() {
}
login(){
this.isLoggedIn = true;
}
logout(){
this.isLoggedIn = false;
}
}
当我尝试访问保护路径,例如 add-merchant-admin 时,浏览器会继续加载页面,消耗大量内存,直到冻结为止。
这些是关于我的应用的详细信息。
节点:6.10.2
os:win32 x64
@ angular / animations:4.2.3
@ angular / common:4.2.3
@ angular / compiler:4.2.3
@ angular / core:4.2.3
@ angular / forms:4.2.3
@ angular / http:4.2.3
@ angular / material:2.0.0-beta.6
@ angular / platform-browser:4.2.3
@ angular / platform-browser-dynamic:4.2.3
@ angular / router:4.2.3
@ angular / cli:1.0.1
@ angular / compiler-cli:4.2.3
验证依赖注入。
正确导入组件。
我不知道该应用程序发生了什么,通常它应该可以正常工作。
希望你们能帮助我。
提前谢谢。
答案 0 :(得分:2)
修改路线如下,
const appRoutes: Routes = [
{
path: 'add-merchant-admin',
component : AddMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'list-merchant-admin',
component : ListMerchantAdminComponent,
canActivate : [AuthGard]
},
{
path: 'login',
component : LoginComponent
},
{
path: 'notfound',
component :NotFoundComponent
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: '**',
redirectTo: 'notfound',
pathMatch: 'full'
},
];
答案 1 :(得分:0)
将AuthGuard更改为:
import { Injectable } from '@angular/core';
import {CanActivate, Router} from "@angular/router";
import {AuthenticationService} from "../authentication-service/authentication.service";
@Injectable()
export class AuthGard implements CanActivate {
constructor(private _authService:AuthenticationService, private _router:Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this._authService.isLoggedIn)
return true;
this._router.navigate(['/login']);
return false;
}
}
在导航方法的参数数组的第一个参数中使用/
作为前缀,告诉angular该路径是绝对的(从根开始)。