I am facing an issue with a service that runs an ajax query and then passes the response to another function for parsing. The initial function returns a promise using the $q library before it is resolved in the parsing function, which then passes the parsed object as a parameter to the resolve method. When my controller uses the .then method to log out the response, everything works perfectly the first time. However, on consecutive calls, it returns the resolve from the initial call before the second call. How can I prevent this from happening?
Below is the code snippet:
app.controller("login", ['$scope','XMLMC', function ($scope,api) {
$scope.login = function() {
//This function is tied to an ng-click directive in the current route template
var params = {
selfServiceInstance: "selfservice",
customerId: $scope.username,
password: $scope.password
};
var authenticated = api.request("session","selfServiceLogon",params).then(function(response) {
console.log(response);
//log the response once the promise is resolved or rejected
});
};
}]);
app.factory("XMLMC", ['$http', '$q', function ($http, $q) {
function XMLMC($http, $q) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
var def = $q.defer();
var P = def.promise;
var that= this;
this.prepareForPost = function(pkg) {
return JSON.stringify(pkg);
};
this.request = function(service, request, params, host, newsession) {
if(request === "analystLogon") {
newsession = true;
}
var call = {
service: service,
method: request,
params: params
};
if(host) {
call.host = host;
} else {
call.host = "localhost";
}
if(newsession) {
call.newsession = "true";
}
var pkg = {
contents: this.prepareForPost(call)
};
$http.post('php/XMLMC/api.php', jQuery.param(pkg)).success(function (response,status) {
that.consume(response, def);
//consume the response, pass the deferred object to resolve later
}).error(function (response,status) {
def.reject(response,status);
});
return P; //return the promise, not the resolved object
};
this.consume = function(response, defer) {
console.log(response);
//log the response that was received. For some reason this log happens after the log in the controller on subsequent calls to this service, not the first call.
var resp = response[0],
digested = {},
i;
digested.status = resp["attrs"]["STATUS"];
var params = resp["children"][0]["children"];
for(i=0; i < params.length; i++) {
var key = params[i]["name"];
var val = params[i]["tagData"];
digested[key] = val;
}
defer.resolve(digested);
//resolve at this point, after the response has been consumed and parsed.
};
}
return new XMLMC($http, $q);
//return new instance of this object for ease of use in controller
}]);