Apologies if this is obvious I am a bit of an Angular\Javascript noob. I have the following service:
MyApp.service('ClientService', function ($http, $q, SharedData) {
this.get = function () {
var deferred = $q.defer();
$http.get("/api/Client/")
.success(function(data, status) {
deferred.resolve(data);
})
.error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
};
this.setCurrentClient = function (clientToSelect) {
var deferred = $q.defer();
var getCurrentClient = this.get();
$http({ method: "POST", url: "/api/Client", data: clientToSelect })
.success(function (data, status) {
//Get the full selected client and all its properties rather than the list version
getCurrentClient.then(
function (client) {
setCurrentClient(client);
setCurrentPeriod(client);
},
function (data) {
//uho something broke.
});
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject(data);
});
return deferred.promise;
}
.....
});
In the this.setCurrentClient function I make a call to the backend via $http and on its asynchronous successful return I call the get function via a variable getCurrentClient. I originally tried to call get() or this.get() directly and neither worked. The context in the .success callback function seems to be the global window context not the service context. The above solution seems a little messy to me. Is there a better way to get the service context and call get() rather than setting a variable with the method (var getCurrentClient = this.get()) and then calling it (getCurrentClient.then()) ? A little lost with javascript\angular scope and contexts...