簡體   English   中英

Angular canActivate 從服務中獲取更新的變量

[英]Angular canActivate get updated variable from service

我有一個來自服務的發布請求,該請求在用戶登錄時返回,我想將 authGuard 設置為僅在用戶登錄時顯示管理面板。我的發布請求如下:

public isLoggedIn: boolean = false;
checkSesh(data: object) {
    const options = {
      headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
      withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`, data, options).subscribe(
      (res) => {
        this.reload = res[0].reload;
        if (this.reload === 0) {
          this.isLoggedIn = true;
        }
      }
    );
  }

我的 authguard 有以下幾點:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {    
    return this.service.isLoggedIn;
  }

但它返回 false(它在訂閱之前獲取布爾值)。

在發布請求運行並且值已更新后,如何更新它?

謝謝

您需要在 canActivate 函數中返回 Observable 作為結果。 因此,您可以將結果映射到 checkSesh 函數中,以返回 true/false。 所以像這樣:

checkSesh(data: object) {
    const options = {
        headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
        withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`, data, options)
        .pipe(
            map((res) => {
                this.reload = res[0].reload;
                if (this.reload === 0) {
                    this.isLoggedIn = true;
                    return true;
                }
                return false;
            })
        );
}

然后就在 canActivate 函數中,您可以執行以下操作:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.service.checkSesh();
}

暫無
暫無

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

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