1

好的,所以我正在尝试设置 $httpBackend 以用作针对 API 进行本地开发的模拟服务器。我在不同的模块中有两个服务:search 和 searchMock:

  • search 返回一个 $resource 对象,该对象在登台或生产环境中公开 API 动词,并按预期工作
  • searchMock 暴露了 $httpBackend ,它反过来用模拟 JSON 对象响应,并按预期工作

我有另一个服务 APIInjector,它根据 Grunt 在构建应用程序时动态包含的配置文件确定当前环境是什么,并相应地注入 search 或 searchMock。

我的问题是,据我从高低搜索中可以看出,$httpBackend 需要在模块的 run 方法中设置。问题是我无法在 APIInjector 的条件逻辑中注入 run 方法。

如果满足开发环境条件,我如何公开 $httpBackend ,否则我的 $resource 服务?请注意,我没有包括调用控制器或 searchService 的代码,但如果需要澄清,我可以。

搜索模拟:

var searchMockService = angular.module('searchMockService', []);

searchMockService.run([
  '$httpBackend', 
  function($httpBackend) {
    results = [{name: 'John'}, {name: 'Jane'}];
    $httpBackend.whenGET('/search').respond(results);
}]);

API注射器:

var APIInjectorService = angular.module('APIInjectorService', [
  'searchService', 
  'searchMockService'
]);

APIInjectorService.factory('APIInjector', [
  '$injector',
  'ENV_CONF',
  function($injector, ENV_CONF) {
    var isDevelopment = ENV_CONF.IS_DEVELOPMENT;

    // Check to see if we're in dev and, if so, inject the local API services
    if (isDevelopment) {
      return {
        Search: // Not sure what to do here to expose searchMock's run method???
      };
    } else {
      return {
        Search: $injector.get('Search') // This returns $resource from the search service, as expected
    };
  }
}]);
4

2 回答 2

1

为了对这个问题提出最后一点,我最终将其提取到我的构建脚本(Grunt)中并完全放弃了上述方法。相反,我将要构建的环境(开发、登台、生产等)作为标志传递给 Grunt,然后在构建期间加载适当的 API 服务。

希望可以帮助其他人尝试实施后端开发!

于 2014-08-07T21:42:56.103 回答
0

As bad as it looks at first place, i'd use the document.write method,if you are not using requirejs(it shouldnt be a problem with requirejs).

  • 1 - bootstrap your ENV_CONF variable in a script tag as first script in HEAD tag.
  • 2 - load all the common scripts
  • 3 - test the ENV_CONF.IS_DEVELOPMENT in another SCRIPT tag.
  • 4 - if true document.write('<script src="angular-mocks.js"></script><script src="main-dev-module.js"></script>')
  • 5 - if false document.write('<script src="main-prod-module.js"></script>')
  • 6 - profit

That way you dont need to deal with ENV_CONF.IS_DEVELOPMENT inside your modules.

html5 boilerplate uses this technique to either fetch jquery from a cdn or locally

https://github.com/h5bp/html5-boilerplate/blob/master/index.html

Edit: I'm sure there are cleaner ways to inject services dynamically in angularjs,but that's what i'd do.I'd like someone to propose a better alternative.

于 2014-05-29T19:19:13.250 回答