0

I have an angular component that calls a service. The component has a method like this:

componentDoThing(id){
    this.member = this.service.getSomeValue(id);
    console.log("component: member: " + this.member);
    //member is undefined
}

And the service:

getSomeValue(id){
    local_http_method.get(/some/url)
         .then(result => {this.something = result});
    console.log("service: this.something:" + this.something);
    // this.something is {"foo":"bar","1":"3"}
    return this.something;

Why is the value undefined in the component, but perfectly well defined in the service?

Dan
  • 12,157
  • 12
  • 50
  • 84
  • This seems like bad practice, you're returning a value that is not guaranteed to be correct since the promise might not be resolved by the time you return the value. But that doesn't explain why the 2 logs give different results. – yi fan song Nov 18 '20 at 20:17
  • 1
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Nov 18 '20 at 20:24
  • 1
    Why is it undefined in one place but defined somewhere else? Luck and timing. Don't depend on those; return a promise from the service function and use `.then(value => /* code that uses value */)`. in the consuming component. – Heretic Monkey Nov 18 '20 at 20:27
  • From your service method, you should `return` your promise so you're able to write `this.service.getSomeValue(id).then((result) => { console.log(result) })`. Or you could use the `async await` approach – Pieterjan Nov 18 '20 at 20:28

0 Answers0