Home > Net >  Pass subscribe response to variable - Angular
Pass subscribe response to variable - Angular

Time:01-06

i trying to pass the subscribe response of my Http.Get to a variable but always i try it the values when comes is undefined

TesteToken() : any {
let token;
this.http.get<any>(`${this.url}/token`).subscribe(res => {
  token = res;
  return token;
});}

but when i put this

 TesteToken() : any {
let token;
this.http.get<any>(`${this.url}/token`).subscribe(res => {
  token = res;
  console.log(token);
});}

then works and the output is in console

CodePudding user response:

You can use this solution (convert obserbable to promise and add async/await):

async TesteToken(): Promise<Something> {
    return await this.http.get<any>(`${this.url}/token`).toPromise();
}

let token =  this.TesteToken();

CodePudding user response:

Issue: You are trying to return async response, like its synchronous.

    TesteToken() : any { // this does not return anything since function ends before a value is returned.
    let token;
    this.http.get<any>(`${this.url}/token`).subscribe(res => {
      token = res;
      return token;  // does nothing
    });
}

Fix: Subscribe where you want to set the value.

TestToken() : Observable<any> { // you can set the type of any
return this.http.get<any>(`${this.url}/token`);
}

To access the value;

// code runs
    this.TestToken().Subscribe((value) => { 
// code runs after value has returned from server
console.log(value); 
})
// code outside subscribe runs first without waiting.
  •  Tags:  
  • Related