[英]Typescript angular guard canactivate
我在路线上有一些警卫,看起来像这样
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;
}
}
}
问题是我有这么多条件,而且对很多行,也许可以做得更短? 谢谢 我什至不知道如何开始
只需反转您的第一个条件并将两者合并为 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)
);
}
}
你可以做的更短一点,但也不会有很大的不同
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.