【问题标题】:IOC in AngularJS (1.x) - How can I achieve?AngularJS (1.x) 中的 IOC - 我该如何实现?
【发布时间】:2016-04-27 16:40:06
【问题描述】:

我正在寻找将IOC 添加到我的angularjs 应用程序的方法。

我的应用是多租户应用,我需要为注册名相同的不同租户使用不同的服务。

我也在使用TypeScript,它适用于在接口上使用具体类型。

我的主要问题是如何决定如何向我的应用程序注册正确的服务。

这是一个例子:

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

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

// here I want to register the same service name with a different implementation
app.service('serviceName', serviceOneFunction); // sometimes I will need this service
app.service('serviceName', serviceTwoFunction); // sometimes I will need this service

我想到的事情:

  1. 添加一些逻辑并为每个源下载正确的 js 文件 - 函数名称将保持不变,我需要找到一种方法来提供包含正确函数的正确 js 文件。

  2. 覆盖注册(例如注册公共服务,然后使用特定实现覆盖注册)。

这两种解决方案都很丑陋,对我来说不可扩展。

我想要一个 IOC 容器或其他一些更好且可扩展的解决方案。

【问题讨论】:

  • 使用什么样的标准来确定您需要哪种服务?应该为每个应用程序定义服务还是需要动态更改它们?
  • 需要在配置中更改服务。由于我想在我的应用程序上注册正确的服务,所以我不会在我的应用程序使用过程中更改此注册。

标签: javascript angularjs typescript inversion-of-control


【解决方案1】:

希望这会对您有所帮助。尝试使用角度工厂。

angular.module('app').factory('tenantService', function() {
  var tenantService = undefined;

  if(tenantType == "1"){
     tenantService = new TenantService1();
  } else if(tenantType == "2"){
     tenantService = new TenantService2();
  } else {
     tenantService = new TenantDefService();
  }
  return tenantService;
});

【讨论】:

  • 这是实现我想要的最简单的方法 - 但这是不可扩展的,这需要对每个租户 x 服务进行特殊处理。还是谢谢。
【解决方案2】:

如果我对问题的理解正确,您可以将服务(实际上是提供者)注册为您在角度配置步骤中配置的提供者。 所以,它可能看起来像这样:

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

// common registrations
app.service('commonService1', commonServiceFunction1);
app.service('commonService2', commonServiceFunction2);
app.service('commonService3', commonServiceFunction3);
app.service('commonService4', commonServiceFunction4);

app.provider('serviceName', function ServiceNameProvider() {
    var service = DefaultService;

    this.setService = function(newService) {
        service = newService
    }

    this.$get = [function() {
        return service;
    }];
});

app.config(["serviceNameProvider", function(serviceNameProvider) {  
    if(someCondition) {
        serviceNameProvider.setService(ServiceImpl1);
    } else {
        serviceNameProvider.setService(ServiceImpl2);
    } 
}]);

服务,工厂只是提供者的语法糖。您可以在 Angular 的配置阶段确定您的服务功能。 ServiceImpl1ServiceImpl2 只是函数,但您可以在那里使用依赖注入,因为它们将被提供者 with $injector.invoke 调用。 Read about providers

【讨论】:

  • 我考虑过使用提供程序,但它不可扩展,这需要对每个租户 x 服务进行特殊处理。还是谢谢。
  • 无论如何,您必须对每个租户进行某种特殊处理,可以为 IoC 或提供商进行配置。您不能将那部分委托给构建过程并使用服务加载不同的模块取决于构建标志吗?
  • 我正在考虑以某种方式加载一个 json 配置,该配置实际上会以某种方式配置一个 ioc 容器并挂钩 angular 的解析器。
猜你喜欢
  • 2012-10-25
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多