[英]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
谢谢 我什至不知道如何开始
Just reverse your first condition and merge the two as one in the map, it should act as before and be more comprehensible:只需反转您的第一个条件并将两者合并为 map 中的一个,它应该像以前一样运行并且更易于理解:
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)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.