【问题标题】:Angular 7 CanActivate Guard for URLAngular 7 CanActivate Guard for URL
【发布时间】:2020-01-08 12:42:04
【问题描述】:

我正在尝试为特定 URL 创建一个 Guard。如果我的 url 包含一个名为“id”的参数,我想检查 Guard。如果是,我想用这个 id 和 id 值重定向到特定的 url,如果不是,我想从服务中运行方法,该方法将创建一个 id 并将其设置为 URL。

我已将 canActivate 附加到我的路线。不幸的是,我坚持创建 Guard 的其余逻辑。我知道有类似 UrlTree 的东西可以重用。任何人都可以帮助创建这种警卫吗?我还在我的代码中添加了 cmets。非常感谢。

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}.

【问题讨论】:

  • 那么这仅适用于单条路线吗?
  • 是的,目前这仅适用于单路。
  • 嗯.. 也有点不清楚。你有问题说:I would like to check in Guard if my url contain a param called "id". If yes, I would like to redirect to specific url,但你说Here I would like to check if my URL has a param "id", then I should allow user to enter.是什么,你喜欢重定向还是让用户进入页面?

标签: angular url guard


【解决方案1】:

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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 2018-03-18
    • 2017-07-24
    • 2021-05-06
    • 1970-01-01
    • 2021-09-11
    • 2019-05-05
    • 2018-05-20
    相关资源
    最近更新 更多