首页 > 解决方案 > VS Code 在 Angular getter 函数中找不到“get”的名称,有什么解决方法吗?

问题描述

我是一个 Angular 新手,致力于用户身份验证(IDE:VS Code)(使用 auth0 作为身份验证服务)。我的问题是,当我尝试使用下面的函数时,“get”、“authenticated”和“boolean”都出现了红色下划线,我不知道发生了什么。基本上,该函数应该检查解析的参数是否为真:

    get authenticated(): boolean {

      return JSON.parse(localStorage.getItem(this._authFlag) || '{}');

    }

VS Code 告诉我它找不到名称“get”和“authenticated”,我假设这会导致 boolean 需要成为类型而不是值的错误。关于我做错了什么的任何想法?这是完整的组件文件:

import { Injectable } from '@angular/core';

//npm install --save @types/auth0-js (CLI cmd)
import * as auth0 from 'auth0-js';

import { environment } from '../../environments/environment';

import{

  Observable,
  BehaviorSubject,
  bindNodeCallback, 
  of
} from 'rxjs';

import { Router } from '@angular/router';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  auth0 = new auth0.WebAuth({

    clientID: environment.auth0.clientID,

    domain: environment.auth0.domain,

    responseType: 'token id_token',

    scope: 'openid profile email'

  });

  //Track whether or not to renew token
  private _authFlag = 'isLoggedIn';
  
  private _userProfileFlag = 'userProfile';


  //Store authentication data & create stream for token
  token$!: Observable<string>;

  //Create stream for user profile data
  userProfile$ = new BehaviorSubject<any>(null);


  //Authentication Navigation
  onAuthSuccessUrl = '/';

  onAuthFailureUrl = '/';

  logoutUrl = environment.auth0.logoutUrl;

  //Create observable of Auth0, then parseHash() function to gather 'auth' results
  parseHash$ = bindNodeCallback(this.auth0.parseHash.bind(this.auth0));

  //Create observable of Auth0 checkSession() function to verify authorization server session and renew tokens
  checkSession$ = bindNodeCallback(this.auth0.checkSession.bind(this.auth0));
  


  constructor(private router: Router) { 

    const userProfile = localStorage.getItem(this._userProfileFlag);

    if (userProfile) {

      this.userProfile$.next(JSON.parse(userProfile));

    }
  }

  login = () => this.auth0.authorize();
  

  handleLoginCallback = () => {

    if (window.location.hash && !this.authenticated) {

      this.parseHash$().subscribe({

        next: authResult => {
          this._setAuth(authResult);

          window.location.hash = '';

          this.router.navigate([this.onAuthSuccessUrl]);

        },

        error: err => this._handleError(err)

      });

    }

  };

  //Save authentication data and update login status subject
  private _setAuth = (authResult: any) => {

    //Observable of token
    this.token$ = of(authResult.accessToken);


    const userProfile = authResult.idTokenPayload;

    //Emit value for user data subject
    this.userProfile$.next(userProfile);

    //save 'userProfile' in 'localStorage'
    localStorage.setItem(this._userProfileFlag, JSON.stringify(userProfile));

    //Set flag in local storage stating that this app is logged in
    localStorage.setItem(this._authFlag, JSON.stringify(true));



    const 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]);

          }

        });

      }

    }

    const logout = () => {

      //Set authentication status flag in local storage to false
      localStorage.setItem(this._authFlag, JSON.stringify(false));

      //remove the userProfile data
      localStorage.removeItem(this._userProfileFlag);

      //refresh, then redirect to homepage
      this.auth0.logout({

        returnTo: this.logoutUrl,

        clientID: environment.auth0.clientID

      });
      
    };

    get authenticated(): boolean {

      return JSON.parse(localStorage.getItem(this._authFlag) || '{}');

    }

  }

  
  //Utility functions
  private _handleError = (err: { error_description: any; }) => {

    if (err.error_description) {

      console.error(`Error: ${err.error_description}`);

    } else {

      console.error(`Error: ${JSON.stringify(err)}`);

    }

  };

}


标签: angularauthenticationvisual-studio-codeauth0getter

解决方案


问题 1authenticatedgetter 放置在错误的位置

从您的代码中,

private _setAuth = (authResult: any) => {
    ...

    get authenticated(): boolean {
        return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
   }
}

问题 1 的解决方案:移出方法的authenticatedgetter _setAuth

private _setAuth = (authResult: any) => {
    ...
}

get authenticated(): boolean {
    return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}

问题 2authenticated :与 getter重复的变量名authenticated

authenticated当你有吸气剂时,你不需要创建变量。否则与变量名冲突

问题 2的解决方案:删除变量声明。

authenticated!: boolean;

推荐阅读