Last active
May 2, 2016 16:06
-
-
Save kazuo/cc4513ae2b27dfbf84cd1b0973405a15 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Analyzes a contrusctor and creates the array and final function for injection | |
// e.g. | |
ServiceInstance.$inject = ['$rootScope', '$q', 'ServiceA', 'ServiceB']; | |
funciton ServiceInstance($rootScope, $q, Service, ServiceB) | |
{ | |
this.fetch = function () {}; | |
// ... whatever logic | |
} | |
// from a provider, we would do... | |
this.$get = ['$rootScope', '$q', 'ServiceA', 'ServiceB', function ($rootScope, $q, ServiceA, ServiceB) { | |
return new ServiceInstance($rootScope, $q, Service, ServiceB); | |
}]; | |
// which is annoying especially when our ServiceInstance already has an $inject property for explicit injection | |
// let's do this instead! | |
this.$get = constructService(ServiceInstance); | |
// when not using injectables argument but instead the service's $inject property, | |
// only call it after the $inject property is set | |
// Or we should really just do it the Angular way... | |
this.$get = ['$injector', function ($injector) { | |
// This is the same as doing module.service | |
return $injector.instantiate(ServiceInstance); | |
}]; | |
// Alternatively, if you want to register it as a factory (useful when wanting to "new" a service when being used in a component) | |
this.$get = ['$rootScope', '$q', 'ServiceA', 'ServiceB', function ($rootScope, $q, Service, ServiceB) { | |
function Factory() | |
{ | |
// define properties | |
} | |
Factory.prototype.fetch = function () { | |
// fetch logic... e.g. | |
return $q.when(ServiceB); | |
}; | |
return Factory; | |
}]; | |
/** | |
* Constructs a service that can be used in a provider's $get property | |
* @param {Function} service | |
* @param {Array} [injectables] | |
* @returns {Array} | |
*/ | |
function constructService(service, injectables) | |
{ | |
if (Array.isArray(service.$inject)) { | |
injectables = angular.copy(service.$inject); | |
} else if (Array.isArray(injectables)) { | |
// do not mutate original | |
injectables = angular.copy(injectables); | |
} else { | |
injectables = []; | |
} | |
injectables.push(function () { | |
var args = [service]; | |
for (var a = 0; a < arguments.length; a++) { | |
args.push(arguments[a]); | |
} | |
return new (service.bind.apply(service, args)); | |
}); | |
return injectables; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment