tjespe tjespe - 24 days ago 8
AngularJS Question

How can I simulate a $http success in angular?

I have a service that I use in several of the controllers in my app.

The service contains a $http call to a php script that returns some important data.

What I want to do is to get that data from the user's

localstorage
if the request fails, and then call all the functions bound to the $http success in all the controllers.

This is what a part of my service looks like:

app.service('initialJSON', ['$http', function ($http) {
var vm = this;
vm.json = $http.get(url);
vm.json.success(function (data) {
if (typeof Storage !== "undefined") {
localStorage.initialJSON = data;
}
})
vm.json.error(function (data, status) {
if (typeof Storage !== "undefined" && "initialJSON" in localStorage) {
// call all success functions in all controllers with the locally saved data
}
});
}]);


As an example the function in this controller should be called:

app.controller('someCtrl', ['initialJSON', function(initialJSON) {
var vm = this;

initialJSON.json.success(function (data) {
// This function should be called and do some things with the data
});

}]);


I don't know if this is possible or how much of my structure I would have to change to make it possible, but if someone has an idea I would really appreciate it.

Answer

Rather than have your controllers re-use the same $http promise, create your own that you will resolve with the results once you've obtained them.

app.service('initialJSON', ['$http', '$q', function ($http, $q) {
  var vm = this;
  var deferred = $q.defer();
  vm.json = deferred.promise;

  var request = $http.get(url);
  request.then(function (data) {
    if (typeof Storage !== "undefined") {
      localStorage.initialJSON = data;
      deferred.resolve(data);
    }
  })
  request.catch(function (data, status) {
    if (typeof Storage !== "undefined" && "initialJSON" in localStorage) {
        deferred.resolve(localStorage.initialJSON);
    }
  });
}]);

If your controllers only care about success the above should work. If you need them to be able to handle errors as well you'll need to extend it in some way to call deferred.reject() after making both attempts to get the data.