我有一个路由守卫,可以在继续之前检查用户是否可以访问资源。订阅后,我检查用户是否有权访问,如果没有,则使用重定向parseUrl
或返回true
。
@Injectable({ providedIn: 'root' })
export class PortfolioGuard implements CanActivate {
constructor(private resourceAccessService: ResourceAccessService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean | UrlTree {
const id = +route.paramMap.get('id');
// return this.resourceAccessService.checkUserAccessToPortfolio(id);
this.resourceAccessService.checkUserAccessToPortfolio(id).subscribe((hasAccess) => {
if (!hasAccess) {
console.log('No access');
return this.router.parseUrl('/');
} else {
console.log('access');
return true;
}
});
}
}
如果我只返回支票,这有效,但我也希望它根据该支票重定向。
@Injectable({ providedIn: 'root' })
export class PortfolioGuard implements CanActivate {
constructor(private resourceAccessService: ResourceAccessService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const id = +route.paramMap.get('id');
return this.resourceAccessService.checkUserAccessToPortfolio(id);
}
}
我在第一块代码中遗漏了什么,我应该从服务中解决订阅...
checkUserAccessToPortfolio(id: number): Observable<boolean> {
const url = this.baseUrl + this.userResourceAccessUrl + '/' + + id + '/portfolio';
return this.http.get<boolean>(url);
}