javascriptangularforgot-password

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


I am trying to validate whether the user exists via his email in order to reset password with 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();
    }

After trying this, my file outputs are:

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

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

Don't know what to do.


Solution

  • You can't get this in a typical function. You can use the arrow function to solve it.

    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