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
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)
);
}
}
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)
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.