【问题标题】:Javascript inheritance and Angular servicesJavascript 继承和 Angular 服务
【发布时间】:2015-07-22 09:35:09
【问题描述】:

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

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;

});

最后,这是我在 Controller 中的使用方式:

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

......

moduleService.prototype.execute("webservice_name.asmx", "webservice_method").then(result);

一切正常,但我对必须使用原型来运行“执行”功能这一事实感到困惑。我做的一切都正确吗?

谢谢

【问题讨论】:

    标签: javascript angularjs inheritance


    【解决方案1】:

    您可以将您的工厂更改为以下..这样不再需要使用原型来调用基础服务方法。

    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();
    

    【讨论】:

    • 是的,这有帮助。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2016-03-29
    • 1970-01-01
    • 2014-09-07
    • 2014-07-10
    • 2020-10-07
    • 1970-01-01
    相关资源
    最近更新 更多