我正在进行一个简单的登录过程,我试图保护某些路径,除非他们经过身份验证 .
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;
}
}
authentication-service
@Injectable()
export class AuthenticationService {
isLoggedIn = false;
constructor() {
}
login(){
this.isLoggedIn = true;
}
logout(){
this.isLoggedIn = false;
}
}
当我尝试访问 guarded path 之类的 add-merchant-admin 时,浏览器会继续加载页面,消耗大量内存直至冻结 .
这些是我的应用程序的详细信息 .
node: 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 @角度/材质: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验证依赖注入 . 组件已正确导入 .
我不知道这个应用程序发生了什么,通常它应该工作 .
希望你们能帮助我 .
非常感谢提前 .
2 回答
修改路由如下,
将AuthGuard更改为:
使用
/
作为导航方法的参数数组的第一个参数中的前缀,您可以告诉角度该路径是绝对的(从根开始) .