2014-06-11 24 views
0

我有兩種不同的藍牙低能耗服務爲我的角應用程序實現。

所以我創建了一個通用的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');

不能實例化模塊,因爲這是在配置階段仍然。

回答

1

你應該注入你的應用程序的$injector(所以它知道你的應用程序可用的服務)。
幸運的是,$injector服務知道如何注入自己:

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