Angularjs 在提供程序的$get方法中注入服务
我的angular应用程序有两种不同的蓝牙低能服务实现 因此,我创建了一个通用的Angularjs 在提供程序的$get方法中注入服务,angularjs,dependency-injection,bluetooth-lowenergy,Angularjs,Dependency Injection,Bluetooth Lowenergy,我的angular应用程序有两种不同的蓝牙低能服务实现 因此,我创建了一个通用的bluetoothServiceProvider,它应该返回蓝牙服务的正确实现。一个是cordovaBluetoothService,另一个是chromeBluetoothService。因此,我检查窗口属性并决定需要哪一个 我知道我可以像这样将这两个服务注入$get函数 this.$get = [ 'chromeBluetoothService', 'cordovaBluetoothService'
bluetoothServiceProvider
,它应该返回蓝牙服务的正确实现。一个是cordovaBluetoothService
,另一个是chromeBluetoothService
。因此,我检查窗口
属性并决定需要哪一个
我知道我可以像这样将这两个服务注入$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');
但它返回一个
未知提供者:chromeBluetoothServiceProvider您应该注入应用程序的$injector
(这样它就知道应用程序可用的服务)。
幸运的是,$injector
服务知道如何注入自己:
this.$get = ['$injector', function ($injector) {
if (window.cordova) {
return $injector.get('cordovaBluetoothService');
else {
return $injector.get('chromeBluetoothService');
}
}