/ / Inyectar un servicio en otro servicio en angularJS - angularjs, angularjs-service

Inyectar un servicio en otro servicio en angularJS - angularjs, angularjs-service

¿Es posible inyectar un servicio en otro servicio en angularJS?

Respuestas

108 para la respuesta № 1

Sí. siga la regla de inyección regular en angularjs.

app.service("service1", function(){});

//Inject service1 into service2
app.service("service2",function(service1){});

Gracias a @simon. Es mejor usar la inyección de matriz para evitar un problema minificador.

  app.service("service2",["service1", function(service1) {}]);

7 para la respuesta № 2

Sí. De esta manera (este es un proveedor, pero se aplica lo mismo)

    module.provider("SomeService", function () {


this.$get = ["$q","$db","$rootScope", "$timeout",
function($q,$db,$rootScope, $timeout) {
return reval;
}
});

En este ejemplo, $db es un servicio declarado en otra parte de la aplicación y inyectado en el proveedor "s $get función.


5 para la respuesta № 3

Para evitar cualquier confusión, creo que esTambién vale la pena mencionar que si está utilizando cualquier otro servicio (por ejemplo, $ http, $ cookies, $ state) en su childService, también debe declararlos explícitamente.

p.ej.

function() {
var childService = function($http, $cookies, parentService) {

// Methods inherited
this.method1Inherited = parentService.method1();
this.method2Inherited = parentService.method2();

// You can always add more functionality to your child service

angular.module("app").service("childService", ["$http", "$cookies", "parentService", childService]);

}());

Puede declarar los servicios que está utilizando dentro de su hijo en una matriz y luego se inyectan automáticamente, o inyectarlos por separado con la anotación $ inject:

childService.$inject = ["$http", "$cookies", "parentService"];
angular.module("app").service("childService ", childService );