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
My requirement is load component B is exactly opposite to above.
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?
canActivate
method has state
property which is of type RouterStateSnapshot. You can make a decision based on state.url
and just return the inverse of hasActiveSummary
based on the route you are reaching.