0

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.

1
  • Please try to convert your login function to the async function. Use the async/await mechanism. 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. Commented Dec 14, 2022 at 4:02

1 Answer 1

1

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')
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.