Javascript继承和Angular服务

Javascript inheritance and Angular services

本文关键字:服务 Angular 继承 Javascript      更新时间:2023-09-26

我试图创建一个通用的服务类,我可以在控制器中使用来获取数据。下面是我的代码:

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;

});然后在一个模块中,我使用baseService来创建模块的特定服务:

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;

});

最后,这是我如何在控制器中使用它:

module.controller('moduleController', function ($scope, moduleService) {

……

moduleService.prototype.execute("webservice_name。asmx"、"webservice_method")(结果);

一切都很好,但我被一个事实所迷惑,我必须使用一个原型来运行"执行"函数。我做的每件事都对吗?

谢谢

您可以将您的工厂更改如下:这样就不再需要使用prototype来调用base 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
alarmsService.prototype = new baseService();
return new alarmsService();