angularJS의 다른 서비스에 하나의 서비스를 주입 할 수 있습니까?
답변
예. angularjs의 일반 주입 규칙을 따르십시오.
app.service('service1', function(){});
//Inject service1 into service2
app.service('service2',function(service1){});
@simon에게 감사드립니다. 최소화 문제를 피하기 위해 배열 주입을 사용하는 것이 좋습니다.
app.service('service2',['service1', function(service1) {}]);
답변
예. 이와 같이 (제공자이지만 동일한 사항이 적용됨)
module.provider('SomeService', function () {
this.$get = ['$q','$db','$rootScope', '$timeout',
function($q,$db,$rootScope, $timeout) {
return reval;
}
});
이 예에서는 $db
앱의 다른 곳에서 선언되고 공급자의 $get
함수에 삽입 된 서비스 입니다.
답변
혼동을 피하기 위해, childService에서 다른 서비스 (예 : $ http, $ cookies, $ state)를 사용하는 경우 명시 적으로 선언해야한다는 점도 언급 할 가치가 있다고 생각합니다.
예 :
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]);
}());
자식 내부에서 사용중인 서비스를 배열로 선언 한 다음 자동으로 주입되거나 $ inject 주석을 사용하여 별도로 주입 할 수 있습니다.
childService.$inject = ["$http", "$cookies", "parentService"];
angular.module("app").service("childService ", childService );