In building out a service layer within an Angular app I noticed a lot of code repetition to create promises therefore tried making a generic getPromise service as 90% of the promises are the same structure.
Although, when returning the promise from the service the function doesn't execute as normal - even though the returned object is the same.
Has anyone tried doing this? E.g.
angular.module('fooApp')
.service('promise', function promise($q, $http) {
return {
getPromise: function (url, data) {
var deferred = $q.defer();
$http.post(url, data)
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
};
})
.service('foo', function foo(config, promise) {
return {
getFoo: function (userId) {
var deferred = $q.defer();
var url = config.svcUser + 'GetFoo';
var data {
userId: userId
};
$http.post(url, data)
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
getFoo2: function (userId) {
var url = config.svcUser + 'GetFoo';
var data {
userId: userId
};
return promise.getPromise(url, data);
}
}
})
.controller('AgenciesCtrl', function ($scope, agency) {
agency.getFoo().then(function (agencies) {
// does fire
});
agency.getFoo2().then(function (foo) {
// does not fire
});
$scope.loadAgency = function (agencyId) {
agency.getFullAgencyProfile(agencyId).then(function (agency) {
$scope.agency = agency;
});
}
});
The issue seems fairly light in this small example but I'm planning on implementing 30+ services so it will reduce code repetition a lot if possible.