首页 > 解决方案 > Angular canActivate 从服务中获取更新的变量

问题描述

我有一个来自服务的发布请求,如果用户登录则返回,我想设置一个 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 (它在订阅之前获取布尔值)。

在发布请求运行并且值更新后如何更新它?

谢谢

标签: angularsubscribecanactivate

解决方案


您需要在 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();
}

推荐阅读