1

I am trying to use a $http call inside an Angular service where the returned promise is handled with a then function. Inside the then function I want to be able to update a variable of the service, however I can't seem to figure how to do this. As you can see in the Plunker below when I try to assign a new value to the testVal variable the assignment doesn't get made. I have been able to make this assignment in the controller by passing the promise back to it and then assigning in the controller's own then function, but I'm trying to figure out how to do it from the service itself, since that is where my model is stored and I would like to keep the controller as bare bones as possible for testing concerns.

console.log(response.data.foo); //Displays "bar"
testVal = response.data.foo; //Doesn't update this.testVal to "bar"?

Plunker

1 Answer 1

2

You should try updating method to:

this.testMethod = function(){
    var self = this;
    var promise = $http.get('http://echo.jsontest.com/foo/bar').then(function(response){
      console.log(response.data.foo); //Displays "bar"
      self.testVal = response.data.foo; 
    })
  }
Sign up to request clarification or add additional context in comments.

2 Comments

That did the trick thank you Nemanja! I'm curious though, why do we need to make a reference to this through self in this case? Can you only reference "this" one function level deep?
You don't have to call variable self, it can be any name you want. The variable is used to save current scope that will be used in another scope (then function in your case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.