我们的项目结构如下:
在用户使用调用Firebase的表单进行身份验证后,必须将用户重定向到只有登录用户才能访问的部件。
如您所见,帐户组件有两个子程序。
我正在寻找一种适当的方法来阻止非用户访问我的网站的保护区,并且不知道我是否需要在组件中调用authService (appComponent?AccountComponent?其中一个组件的OnInit?)还是在路由定义中使用或CanActivate或CanActivateChild?
发布于 2016-12-01 13:46:30
使用CanActivate路由警卫。
假设用户身份验证后的路由是http://localhost:3000/#/dashboard
下面是如何防止仪表板路由(与AccountComponent及其子节点相关),如果用户未经过身份验证,将被访问。
路线上的:
{ path: 'dashboard',
canActivate: [ AuthService ],
component: AccountComponent,
children: [
ProfileComponent,
FilesComponent
]
}并实现身份验证服务中的CanActivate:
@Injectable()
export class AuthService implements CanActivate {
isAuthenticated(): boolean{
// auth logic
}
canActivate(): boolean{
const isAuth = this.isAuthenticated();
if(!isAuth){
//if not authenticated do something. e.g redirect to login page
this._router.navigate(['','/login'])
}
return isAuth;
}
}https://stackoverflow.com/questions/40911949
复制相似问题