简体   繁体   中英

What is the right way to handle duplicated factory in angularjs?

instantiate angular's factory n number of times.

example:

app.factory('FooService', function(){
   return {
       hello: function() {
           return "hello foo first";
       }
   } 
});

app.factory('FooService', function(){
   return {
       hello: function(){
           return "hello foo second";
       }
   } 
});

Second service will override the first one - demo at http://plnkr.co/edit/FNqDdH5w5ArbJEBsgsLc?p=preview

The example is just to illustrate the problem but the real world problem is different developer defined the service with same name which make it very hard to troubleshoot.

What is the right way to handle duplicated factory in angularjs? (or prevent or detect it easily)

I'm not sure what is the right way, however you can ask the injector if a particular service exists or not.

var myModule = angular.module('myModule', [])
        .factory('test', function () {
            return { test: 'test' };    
        });

var injector = angular.injector(['myModule']);

console.log(injector.has('test')); //true

Also note that the service must have been defined prior to the injector retrieval meaning that you shouldn't try to cache the injector , just query it every time.

This is a perfect use case for a Decorator .

Decorator
A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.

How to use it:

app.config(function($provide) {
  $provide.decorator('FooService', FooServiceDecorator);

  function FooServiceDecorator($delegate) {
    $delegate.hello = function() {
      return "hello foo second";
    };
    return $delegate;
  }
});

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM