'Typescript angular guard canactivate
I have some guard on route that looks like this
export class GuardService implements CanActivate {
constructor(private router: Router, private apiService: InfoService) { }
canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
const { id, type } = route.params;
if (Object.keys(CustomerType).includes(type)) {
return this.apiService.get(id).pipe(
map((overview) => {
if (type === 'additional') {
if (overview.main === null) {
return this.navigate([etc])
}
return true;
}
return true;
}),
catchError(() => false)
);
} else {
return false;
}
}
}
The problem is that I have so many conditions, and to many lines, maybe it can be made shorter? Thanks I dont know how to even start
Solution 1:[1]
Just reverse your first condition and merge the two as one in the map, it should act as before and be more comprehensible :
export class GuardService implements CanActivate {
constructor(private router: Router, private apiService: InfoService) { }
canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
const { id, type } = route.params;
if (!Object.keys(CustomerType).includes(type)) {
return false;
}
return this.apiService.get(id).pipe(
map((overview) => {
if (type === 'additional' && overview.main === null) {
return this.navigate([etc])
}
return true;
}),
catchError(() => false)
);
}
}
Solution 2:[2]
You can do it a little bit shorter but nor a huge difference
canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
const { id, type } = route.params;
if (!Object.keys(CustomerType).includes(type)) {
return false;
}
return this.apiService.get(id).pipe(
map((overview) => {
if (type === 'additional' && overview.main === null) {
return this.navigate([etc])
}
return true;
}),
catchError(() => false)
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quentin Grisel |
| Solution 2 | Zerotwelve |
