I am trying to create a generic service class that I can use in Controllers to get data. Here is my code:
appClasses.factory('baseService', function ($http, $q) {
var apiUrl = "http://localhost:1234/services/";
// instantiate initial object
var baseService = function () {
};
baseService.prototype.execute = function (webService, method, params) {
params = typeof params !== "undefined" ? params : {};
var deferred = $q.defer();
var response = $http({
method: "post",
dataType: "json",
data: JSON.stringify(params),
headers: {
'Content-Type': "application/json; charset=utf-8",
},
url: apiUrl + webService + "/" + method
});
response.success(function (data) {
deferred.resolve(data);
});
response.error(function (data) {
alert('Error');
});
// Return the promise to the controller
return deferred.promise;
};
return baseService;
}); Then in a module I use baseService to create module's specific service:
module.factory("moduleService", function (baseService) {
// create our new custom object that reuse the original object constructor
var alarmsService = function () {
baseService.apply(this, arguments);
};
// reuse the original object prototype
moduleService.prototype = new baseService();
return moduleService;
});
Finally, here is how I use it in Controller:
module.controller('moduleController', function ($scope, moduleService) {
......
moduleService.prototype.execute("webservice_name.asmx", "webservice_method").then(result);
Everything works fine, but I am confused by a fact that I have to use a prototype to run "execute" function. Am I doing everything correctly?
Thanks