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

7
  • foo= response.body.foo; is executed AFTER the return statement. That's why is always an empty string Commented Oct 8, 2018 at 11:59
  • The code you provided is in a service or in a component.? Commented Oct 8, 2018 at 12:01
  • @SandipJaiswal it's componennt Commented Oct 8, 2018 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. Commented Oct 8, 2018 at 12:04
  • 3
    Possible duplicate of How do I return the response from an asynchronous call? Commented Oct 8, 2018 at 12:04

3 Answers 3

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 !

Sign up to request clarification or add additional context in comments.

1 Comment

Where does the variable "foo" come from in your code above?
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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.