我正在尝试使用 Angular 4 实现登录功能,但是当我使用 canActivate Guard 时,它会导致我进入空白页面,请帮助我
这是我的登录服务
isAuthenticated(){
return localStorage.getItem('token') != null ;
}
Run Code Online (Sandbox Code Playgroud)
这是可以激活守卫的
canActivate(route : ActivatedRouteSnapshot , state : RouterStateSnapshot){
return this.loginservice.isAuthenticated();
}
Run Code Online (Sandbox Code Playgroud)
这是路由器模块
const appRoutes: Routes = [
{path : '' , redirectTo:'/login', pathMatch :'full' },
{path : 'login' , component : LoginComponent },
{path : 'home' , component : HomeComponent, canActivate : [AuthGuard] ,children :[
{path : 'adduser' , component : AdduserComponent },
]
Run Code Online (Sandbox Code Playgroud)
如果您未经身份验证或未经授权,您的 AuthGuard 应该将您重定向到默认页面。
constructor( private loginservice: LoginService, private router: Router) {
}
public canActivate(route : ActivatedRouteSnapshot , state : RouterStateSnapshot){
if(!this.loginservice.isAuthenticated()) {
this.router.navigate(['login']); // choose either default route like here
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2979 次 |
| 最近记录: |