JavaScript的服务:如何提供()方法,像一个对象的构造?对象、方法、JavaScript

2023-09-13 05:04:46 作者:放肆的年华

我想创建一个服务,将创建an接口AngularJS的 $ HTTP 基于此。我想使用依赖注入,而无需重新编写单独的函数调用,并保持$ C $注入服务c清洁。要做到这一点,我提供了创建一个变量,就像这样$ HTTP对象共同的服务:

I would like to create a service that will create an interface to AngularJS's $http based on this. I would like to use dependency injection to inject the service without re-writing individual function calls and keeping the code clean. To do this I am providing a common service that creates a variable to the $http object like this:

commonService = function(...) {
return {
    ...
    $http: $http
}

然后我用常见。$ HTTP 无处不在的code。要改变$ HTTP从AngularJS $ HTTP到我的HTTPService,我只需要改变一个地方。 HttpService的是这样的:

Then I use common.$http everywhere in the code. To change $http from AngularJS $http to my httpService, I need to only change it in one place. httpService looks like this:

function httpService($http, $q, pendingRequests, $interval) {
var get = function(url) {
    ...
    return requestPromise;
};

var service = {
    get:get
};

return service;

}

这适用于以 $ http.get电话(),但即将 $ HTTP调用({方法是什么:'得到',网址: '...'});

是否可以提供()方法,这是真正的HTTPService()()?否则,它会调用该方法AngularJs HTTPService在()。

Is it possible to provide the () method, which is really httpService()()? Otherwise it would call the AngularJs method httpService().

推荐答案

您可以只返回一个对象的函数。您可以将属性添加到您的函数

You can just return a function instead of an object. You can add the properties to your function

function httpService($http, $q, pendingRequests, $interval) {
   var get = function(url) {
      ...
      return requestPromise;
   };

  // Instead of returning an object, return a function
  var service = function() {
    // do whatever you want here
  };

  service.get = get;

  // Add more properties to service as needed

  return service;
}