Javascript继承和Angular服务
Javascript inheritance and Angular services
我试图创建一个通用的服务类,我可以在控制器中使用来获取数据。下面是我的代码:
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();
相关文章:
- 使用angular.js问题的JavaSpringREST服务
- Angular使服务可以从任何地方访问
- Angular 2和服务单元测试
- Angular js-尚未添加PUT请求到服务的URL
- 可以't访问Angular.js服务中的功能
- 通过服务Angular向服务器发送$routeParam
- chrome.storage.sync.get未返回值-Angular服务
- 如何在angular中使构造函数之外的服务可用
- Http服务工厂将未定义的返回到Angular中的控制器
- 如何调用用nodejs编写的服务形式angular
- 由控制器调用的服务更改时,Angular未更新视图
- 正在Angular 2中的扩展RouterOutlet中导入自定义服务以进行身份验证
- 将Browserify与Angular JS结合使用--将服务传递到控制器中
- AngularJS剑道网格绑定到angular服务webapi-当使用[fromuri]进行解析时,排序总是为null
- Angular JS$编译服务导致$watch内存泄漏
- 如何在angular js中的工厂/服务中使用$cookie
- angular如何在我的情况下设置服务
- 在一个服务中引用多个API调用(Angular)
- 使用web服务Java-angular时出现错误404
- $http服务angular不工作