簡體   English   中英

Angular 7 CanActivate Guard for URL

[英]Angular 7 CanActivate Guard for URL

我正在嘗試為特定的URL創建一個Guard。 我想在Guard中檢查我的URL是否包含一個名為“ id”的參數。 如果是,我想使用此id和id值重定向到特定的url,否則,我想從服務運行方法,該方法將創建一個id並將其設置為URL。

我已將canActivate附加到我的路線上。 不幸的是,我在創建Guard的其余邏輯時陷入困境。 我知道有些東西可以重復使用,例如UrlTree。 任何人都可以幫助創建此類Guard? 我還在代碼中添加了注釋。 非常感謝。

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

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM