如何对授权逻辑不同的不同路由使用相同的路由保护
对于我的 Angular 6 项目,我有一个 canactivate AuthGuard 来加载 ComponentA。
我想知道我可以对组件 B 使用相同的 AuthGuard 吗?它的授权逻辑与组件 A 完全相反?
假设授权组件 A 的逻辑如下:
- 从 API 服务获取摘要项 HTTP GET 调用
- 迭代这些项并检查激活状态。如果激活状态为“ACTIVE”,则返回 true
- 如果没有返回摘要项且激活状态不是“ACTIVE”,则返回 false 并仅显示登录页面。
我的要求是加载组件B与上面完全相反。
- 显示组件 B 如果没有返回摘要项且激活状态不是“ACTIVE”,则不加载该组件并仅显示登录页面
- 。如果存在摘要项且激活状态为“ACTIVE”,则仅显示登录页面。
组件 A 现有的 auth.guard.ts:
export class AuthGuard implements CanActivate {
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean>
{
return this.checkAuthorization();
}
checkAuthorization():Observable<boolean>{
let hasActiveSummary:boolean=false;
return this.apiService.getSummary(url)
.pipe(
map((data:any) => {
console.log("Summary list:", data);
if(data.length > 0){
for (let i=0; i< data.length; i++) {
if(data[i].activationStatus ==='ACTIVE') {
hasActiveSummary=true;
return true;
}
}
}
if(!hasActiveSummary){
this.router.navigate(['/login']);
return false;
}
})
)
}
我想知道我可以使用相同的身份验证防护吗?如果可以的话,该怎么办呢?
For my Angular 6 project, I have one canactivate AuthGuard to load ComponentA.
I want to know can I use the same AuthGuard for component B where it's the authorization logic is exactly opposite to component A?
Let's say the logic to authorize component A as follows
- Get summary items from API service HTTP GET call
- Iterate on the items and check the activationStatus. If activation status is 'ACTIVE' return true
- If no summary items are returned and activation status is not 'ACTIVE', return false and just show the login page.
My requirement is load component B is exactly opposite to above.
- Show component B If no summary items are returned and activation status is not 'ACTIVE', do not load the component and just show the login page
- If summary items are present and activation status is 'ACTIVE' just show login page.
Existing auth.guard.ts
for component A:
export class AuthGuard implements CanActivate {
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean>
{
return this.checkAuthorization();
}
checkAuthorization():Observable<boolean>{
let hasActiveSummary:boolean=false;
return this.apiService.getSummary(url)
.pipe(
map((data:any) => {
console.log("Summary list:", data);
if(data.length > 0){
for (let i=0; i< data.length; i++) {
if(data[i].activationStatus ==='ACTIVE') {
hasActiveSummary=true;
return true;
}
}
}
if(!hasActiveSummary){
this.router.navigate(['/login']);
return false;
}
})
)
}
I would like to know can I use the same auth guard? If so, how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
canActivate
方法具有state
属性,其类型为 RouterStateSnapshot 。您可以根据state.url
做出决定,并根据您要到达的路线返回hasActiveSummary
的倒数。canActivate
method hasstate
property which is of type RouterStateSnapshot. You can make a decision based onstate.url
and just return the inverse ofhasActiveSummary
based on the route you are reaching.