0

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

1 Answer 1

1

You can change your factory to followings.. this way no longer need to use prototype any more to call base service method .

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
alarmsService.prototype = new baseService();

return new alarmsService();
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that helped. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.