Search code examples
javascriptangularjsangularjs-service

How To Reference an Angular Services's Variable from a Promise then function inside the Service?


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


Solution

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