angular - Angular 7 CanActivate Guard for URL
问题描述
我正在尝试为特定 URL 创建一个 Guard。如果我的 url 包含一个名为“id”的参数,我想检查 Guard。如果是,我想用这个 id 和 id 值重定向到特定的 url,如果不是,我想从服务运行方法,该方法将创建一个 id 并将其设置为 URL。
我已将 canActivate 附加到我的路线。不幸的是,我坚持创建 Guard 的其余逻辑。我知道有类似 UrlTree 的东西可以重用。任何人都可以帮助创建这种警卫吗?我还在我的代码中添加了注释。非常感谢。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<UrlTree> {
const createContract = from(this._service.createNewContract());
if(this.route.snapshot.queryParams['id']) {
//Here I would like to check if my URL has a param "id", then I should allow user to enter.
}
//In case there is no such param with any value, I need to run method from service which in response will give me an id value, and I need to attach it to current URL with ?id={value}.
解决方案
假设负责为您提供 ID 的服务名为“getIdService”,方法名为“getId”,我会这样做:
constructor(private router: Router, private getIdService: SomeService) {}
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(this.route.snapshot.queryParams['id'] != null) { // id 0 is valid
return true;
}
// here get your ID from your service
this.getIdService.getId().pipe(take(1)).subscribe((id: number) => {
this.router.navigateByUrl('yourURL?id=' + id)
});
return false;
}
希望能帮助到你。
推荐阅读
- unit-testing - 如何在 Go 中对 C 绑定实现进行单元测试/模拟?
- java - Extract submap from a map that contains only duplicate values
- r - 从文件名字符串中提取日期
- python - Networkx 在图中查找不同最短路径之间的公共节点 - 是否有替代解决方案?
- react-native - 如何在 React Native 中将样式表传递给本地 SVG 矢量图像?
- javascript - 如何在 Next 内联 sass 样式中使用变量?
- python - 关于 $TF_PYTHONIOENCODING 的 Mac 终端错误;?
- game-development - 乒乓球戈多重置场景
- python - Django Annotate foreign key - 对象的用户特定状态
- laravel - 如何在 Vue 中将带有 Image 和其他类型输入的表单发布到 API Laravel?