【问题标题】:Angular canActivate get updated variable from serviceAngular canActivate 从服务中获取更新的变量
【发布时间】:2021-01-03 17:32:38
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: angular subscribe canactivate


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多