Home > Mobile >  Angular HTTP request returns undefined the first time
Angular HTTP request returns undefined the first time

Time:12-14

I have a service with such a HTTP request: `

    login(email:any,password:any){
          this.http.post<{token:string}>('http://localhost:3000/login',{payload:{email,password}},{
          headers:new HttpHeaders({'Content-Type':'application/json'})
        }).pipe().subscribe(res=>{this.token=res.token})
    }

a variavle private token!: string; and a helper function:

    getToken() {
        console.log(this.token)
        return this.token;
      }

`

The problem is that when the first time I call getToken() I get an Undefined and only if I call it one more time I get a valid value.

CodePudding user response:

Please make sure that the login function and API call has to be completed before making a call to getToken function. There is a chance of delay since it's an API call.

Saving tokens in a local variable isn't a good practice since you need to call the API when refreshing the browser. Try to save tokens in localStorage rather than saving in a local variable.

login(email:any,password:any){
    setTimeout(()=>{
        this.http.post<{token:string}>('http://localhost:3000/login',{payload:{email,password}},{
            headers:new HttpHeaders({'Content-Type':'application/json'})
        }).pipe().subscribe(res=>{this.token=res.token})
    },3000)
}

OR

 login(email:any,password:any){
    this.http.post<{token:string}>('http://localhost:3000/login',{payload:{email,password}},{
        headers:new HttpHeaders({'Content-Type':'application/json'})
    }).pipe().subscribe(res=>{ localStorage.setItem('token', res.token);
    })
}

getToken() {
    return localStorage.getItem('token')
}

CodePudding user response:

It looks like the issue is that the getToken function is being called before the HTTP request in the login function has completed, so the token variable hasn't been set yet. One way to fix this would be to make the getToken function return the observable from the HTTP request in the login function, and then subscribe to that observable in the component where you're calling getToken. That way, the token will be set before getToken is called. Here's an example of how that might look:

login(email:any,password:any){
      return this.http.post<{token:string}>('http://localhost:3000/login',{payload:{email,password}},{
      headers:new HttpHeaders({'Content-Type':'application/json'})
    }).pipe();
}

getToken() {
    return this.login(email, password).pipe(
        map(res => res.token)
    );
}

In the component where you're calling getToken, you would then subscribe to the observable returned by getToken to get the token:

this.service.getToken().subscribe(token => {
    console.log(token);
    // Use the token here
});

Hope that helps! Let me know if you have any other questions.

  • Related