Reputation: 203
I have created an angular service which is basically a wrapper for another service that makes $resource requests for json data. This 'wrapper service' does some data formatting and then returns the result to my controller.
My problem is that I am struggling to populate my $scope variable (always undefined) in my controller from the function in the 'wrapper' service I have created. I have tried a little with the Deferred API, but I can only successfully get my data in the controller if I call the promise.then method in my controller(without formatting it) which defeats the purpose.
How do I return a formatted list to my controller? I have written a Plunker below which doesn't compile but contains the gist of what I am trying to achieve.
http://plnkr.co/edit/AGyyqvawpnBmKXTcvGkJ?p=info
Upvotes: 0
Views: 111
Reputation: 6269
It's a bit difficult without being able to compile the plunkr, but could you tell me if this works:
factory.js:
routingRulesHelper.factory('ruleSetQueryWrapper', ['$q','RuleSets',
function($q, RuleSets) {
var formatResults = function (ruleSet) {
var aRuleSchedule = {};
//format the payload to correct data ...........
return aRuleSchedule;
};
return {
getRuleSetById: function(ruleSetId){
var deferred = $q.defer();
var ruleset = RuleSets.query({ruleSetId: ruleSetId}, function(ruleSet) {
deferred.resolve(formatResults(ruleSet));
}, function(response) {
//404 or bad
if(response.status === 404) {
console.log("HTTP Error", response.status);
}
deferred.reject();
});
return deferred.promise;
}
}}]);
controller.js:
routingRulesControllers.controller('RulesDisplayCtrl', ['$scope', '$location', '$routeParams', 'RuleSets', 'ruleSetQueryWrapper',
function($scope, $location, $routeParams, RuleSets, ruleSetQueryWrapper) {
$scope.formattedResults = null;
if($routeParams.ruleSetId) {
ruleSetQueryWrapper.getRuleSetById($routeParams.ruleSetId).then(function(results) {
$scope.formattedResults = results;
});
}
}]);
Upvotes: 1
Reputation: 42669
I believe you should instead of this
deferred.resolve(ruleSet)
do
deferred.resolve(formatResults(ruleset))
also you are not returning the deferred.promise in the getRuleSetById
service method.
Upvotes: 0