2

I have some problem returning a string from my request.

getTest(id: string): string {
  let foo: string = '';
  this.service.testProfile(id).subscribe(
    response => {
      foo = response.body.foo;
    },
    error => {
      console.log(error);
    }
  )
  return foo;
}

I want to init foo to my response. foo and then just to return new value of foo. Everything work but there is no result, any idea what I'm doing wrong?

Thank

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
mrkibzk
  • 227
  • 4
  • 17
  • `foo= response.body.foo;` is executed AFTER the return statement. That's why is always an empty string – Jacopo Sciampi Oct 08 '18 at 11:59
  • The code you provided is in a service or in a component.? – Sandip Jaiswal Oct 08 '18 at 12:01
  • @SandipJaiswal it's componennt – mrkibzk Oct 08 '18 at 12:02
  • So why you are returning? Just assign in a property of your component. When component value will change your value will reflect on your DOM. Observables are asynchronous so if you will return then it will return a empty string. – Sandip Jaiswal Oct 08 '18 at 12:04
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – lealceldeiro Oct 08 '18 at 12:04
  • Use this implementation instead: `getTest(id: string): Observable { return this.service.testProfile(id).pipe(map(response => response.body.foo)); }` – SiddAjmera Oct 08 '18 at 12:06
  • can you please add the code snippet for this.service.testProfile ? That is the implementation. – Sandeep Kamath Oct 08 '18 at 12:12

3 Answers3

1

I resolved with Promise

getTest(id: string): Promise<any>  {
 return new Promise((resolve,reject) => {
  this.service.testProfile(id).subscribe(
   response => {
    foo = response.body.foo;
   },
   error => {
    console.log(error);
   }
   )
  }
  )
 }

Thanks everybody !

mrkibzk
  • 227
  • 4
  • 17
0

You return a string which must still be filled (and thus is empty) as the async code to do so hasn't completed yet by the time you return. What you should return is an observable and emit the right string on it in the subscribe(...) call.

Bartios
  • 99
  • 5
0

Change your code like this and try..

getTest(id: string): string {
  this.service.testProfile(id).subscribe(
    response =>  response.body.foo,
    error => {
      console.log(error);
      return '';
    }
  )
}