In my recent development project, I created an angular service with the purpose of loading customer details through http requests and storing them for future use using a singleton pattern.
However, I encountered an issue where the variable intended to hold the fetched data becomes undefined upon successful completion of the http call, resulting in an error being thrown.
Below is the snippet of code responsible for this functionality:
NBApp.service("serverDataService", ['$http', '$q', function ($http, $q) {
var currentMemberDetails = [];
this.currentMember = function (){
if (this.currentMemberDetails.length>0)
return this.currentMemberDetails[0];
return null;
};
this.getMemberDetails = function (cardId) {
//TBD - call members details web service
var deferred = $q.defer();
$http({
method: 'GET',
url: 'resources/customer.json'
}).then
(
function success(response) {
this.currentMemberDetails.push(response.data);
deferred.resolve(data);
},
function failure(response) {
deferred.reject(response);
}
);
return deferred.promise;
};
}]);
The Chrome dev console confirms that currentMemberDetails
remains undefined after the http call is made.