palig
palig

Reputation: 7681

Angular IoC best practice

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

Answers (1)

FrailWords
FrailWords

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

Related Questions