0

I am trying to write a function to be able to retain the value from Observable/Subscribe or Promise/Then. Here's the scenario:

var retValue is of string type.

CallService() :return string
{
  this.http.get('http://api/..').Subscribe(data=> 
   {
    ......
     this.retValue = data[0]  `=>value can be accessed here`
   }

    return this.retValue -> HOW CAN I GET THE VALUE HERE?
}

It comes as Undefined. I know it's to do with mixing sync and async calls but what if we are in a scenario where we can't directly bind it to a component but have to get a value out of it? Let's say an ANGULAR PIPE where user passes in the data, we call the service and we need to pass the data back?

Thanks guys.

David Les
  • 1
  • 1
  • It's an async call man, you won't be ever able to do that. you have to subscribe to that service call and then, take the values from there inside, same than promises – Alejandro Lora Dec 06 '17 at 17:01
  • The service should be returning an observable. The component then subscribes to that observable. Now the component has the data – LLai Dec 06 '17 at 17:01
  • You should process the data in the `Subscribe` handler, or wrap the code that you want to execute in an arrow method and call that method inside of `Subscribe`. – ConnorsFan Dec 06 '17 at 17:05
  • What if we are in a scenario where we can't directly bind it to a component but have to get a value out of it? Let's say an ANGULAR PIPE where user passes in the data, we call the service and we need to pass the data back? – David Les Dec 06 '17 at 17:31

0 Answers0