【发布时间】: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