Reputation: 7681
What's the best practice in AngularJS when one needs to use a different implementation of a service/factory depending on the environment.
Let's say I have a service MessageService
, which is injecting some other service, but based on the device/platform, it should use WebService
vs. MobileService
.
Here's what I do now:
angular
.module('message')
.service('MessageService', messageService);
var service = 'WebService';
if (mobileDevice) {
service = 'MobileService';
}
messageService.$inject = [service];
function messageService(service) {
service.call(); // use the shared interface for both services inside this service
}
Is there a better - more elegant - way to do this?
Upvotes: 1
Views: 898
Reputation: 926
You can use the module's 'config' block to do this using a 'provider' like here -
angular.module('app').config(['$provide', '$injector', 'mobileDevice',
function($provide, $injector, mobileDevice) {
$provide.value('MessageService', (mobileDevice) ? $injector.get('MobileService') : $injector.get('WebService'));
}
]);
This is assuming that 'mobileDevice' is an angular constant.
Now you can inject 'MessageService' to do what you wanted.
Upvotes: 1