【问题标题】:Inject Service in Provider`s $get method在 Provider 的 $get 方法中注入服务
【发布时间】:2014-06-11 07:58:09
【问题描述】:

我的 Angular 应用程序有两种不同的低功耗蓝牙服务实现。

所以我创建了一个通用的bluetoothServiceProvider,它应该返回蓝牙服务的正确实现。一个是cordovaBluetoothService,另一个是chromeBluetoothService。所以我检查了window 属性并决定我需要哪一个。

我知道我可以将这两个服务注入到 $get 函数中

this.$get = [
    'chromeBluetoothService',
    'cordovaBluetoothService',
    function(chromeBtS, cordovaBtS) {
        if(window.cordova) {
            return cordovaBtS;
        else {
            return chromeBtS;
        }
    }
];

但这并不是最优的,因为两个依赖项都在注入时被实例化(我不想在实现中进行特征检测),所以我希望它们在 if 子句中被实例化。我该怎么做?

我试过了:

var $injector = angular.injector();
return $injector.get('chromeBluetoothService');

但它返回一个Unknown provider: chromeBluetoothServiceProvider <- chromeBluetoothService

如果我这样做:var $injector = angular.injector('myApp.services');

它无法实例化模块,因为这仍然是配置阶段。

【问题讨论】:

    标签: angularjs dependency-injection bluetooth-lowenergy


    【解决方案1】:

    您应该注入您应用的$injector(以便它知道您的应用可用的服务)。
    幸运的是,$injector 服务知道如何注入自己:

    this.$get = ['$injector', function ($injector) {
        if (window.cordova) {
            return $injector.get('cordovaBluetoothService');
        else {
            return $injector.get('chromeBluetoothService');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      相关资源
      最近更新 更多