javascript TypeError:无法读取未定义的属性(阅读“API_url”)

ffvjumwh  于 2023-01-08  发布在  Java
关注(0)|答案(1)|浏览(164)

我正在尝试通过电子邮件验证用户是否存在,以便使用AngularJS重置密码。

private api_url = AppSettings.API_ENDPOINT + 'user-info/email_validate';

......


  async function sendRequest<T>(email:string):Promise<T>{
      // console.log(this.api_url);
      const res = await fetch (this.api_url, {
        method:"post",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
          email: email,
        })
      }).then((res) => {
        if(!res.ok){
          console.log("ERROR");
          return res;
        }
        return res;
      })

      return res.json();
    }

尝试此操作后,我的文件输出为:

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'api_url')

TypeError: Cannot read properties of undefined (reading 'api_url')

不知道该怎么办。

yqkkidmi

yqkkidmi1#

this在典型的函数中是得不到的,可以用箭头函数来求解。

class Demo {
  private api_url = `${AppSettings.API_ENDPOINT}user-info/email_validate`;

  // ....

  sendRequest = async <T>(email: string): Promise<T> => {
    // console.log(this.api_url);
    const res = await fetch(this.api_url, {
      body: JSON.stringify({
        email,
      }),
      headers: { 'Content-Type': 'application/json' },
      method: 'post',
    }).then((res) => {
      if (!res.ok) {
        console.log('ERROR');

        return res;
      }

      return res;
    });

    return res.json();
  };
}

For more information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_in_arrow_functions

相关问题