You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code无法识别Angular getter函数中的get等标识符,该如何修复?

问题根源

你出现报错的核心原因是类成员的定义位置错误:

  • TypeScript 类的 getter/setter、普通成员方法都必须直接定义在类的作用域下,不能嵌套在其他类方法内部。你现在把authenticated getter、renewAuth方法、logout方法都写在了_setAuth方法的内部,属于非法语法,IDE 自然无法识别get关键字、authenticated成员,还会把类型标注boolean误认为你要声明变量的值。
  • 额外存在逻辑漏洞:getter 中localStorage.getItem取值失败时的默认值写为'{}',空对象转布尔值永远为true,会导致登录状态判断完全失效。

修正方案

  1. 把authenticated getter、renewAuth、logout三个成员从_setAuth方法中移出,放到和login、handleLoginCallback平级的类直接作用域下
  2. 修正 getter 的默认返回值为'false'

修正后的关键代码片段

// 放在AuthService类的直接作用域下,不要嵌套在其他方法内
get authenticated(): boolean {
  // 把默认值从'{}'改成'false'
  return JSON.parse(localStorage.getItem(this._authFlag) || 'false');
}

renewAuth = () => {
  if (this.authenticated) {
    this.checkSession$({}).subscribe({
      next: authResult => this._setAuth(authResult),
      error: err => {
        localStorage.removeItem(this._authFlag);
        localStorage.removeItem(this._userProfileFlag);
        this.router.navigate([this.onAuthFailureUrl]);
      }
    });
  }
}

logout = () => {
  localStorage.setItem(this._authFlag, JSON.stringify(false));
  localStorage.removeItem(this._userProfileFlag);
  this.auth0.logout({
    returnTo: this.logoutUrl,
    clientID: environment.auth0.clientID
  });
};

// 原来的_setAuth方法里删掉上面三个成员的代码,保留原有逻辑即可
private _setAuth = (authResult: any) => {
  this.token$ = of(authResult.accessToken);
  const userProfile = authResult.idTokenPayload;
  this.userProfile$.next(userProfile);
  localStorage.setItem(this._userProfileFlag, JSON.stringify(userProfile));
  localStorage.setItem(this._authFlag, JSON.stringify(true));
}

内容的提问来源于stack exchange,提问作者p4yner56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:15:04