首页 > 解决方案 > 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}.

标签: angularurlguard

解决方案


假设负责为您提供 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;
  }

希望能帮助到你。


推荐阅读