Wprowadzanie usługi do innego serwisu w angularJS

Czy jest możliwe wstrzyknięcie jednej usługi do innej usługi w angularJS?

Author: Le Garden Fox, 2014-01-08

3 answers

Tak. w angularjs należy przestrzegać zasady regularnego wstrzykiwania.

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

//Inject service1 into service2
app.service('service2',function(service1){});
Dzięki @ simon. Lepiej jest użyć Array injection, aby uniknąć problemu minifying.
  app.service('service2',['service1', function(service1) {}]);
 118
Author: Alborz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-08 19:35:14

Tak. W ten sposób (jest to dostawca, ale to samo dotyczy)

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


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

W tym przykładzie, {[1] } jest usługą zadeklarowaną gdzie indziej w aplikacji i injected into the provider ' s $get function.

 8
Author: Pauli Price,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-08 19:32:42

Aby uniknąć nieporozumień, myślę, że warto wspomnieć również o tym, że jeśli korzystasz z innych Usług (np. $http, $ cookies, $state) w serwisie dziecięcym, to musisz je wyraźnie zadeklarować.

Np.

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]);

}());

Możesz albo zadeklarować usługi, których używasz wewnątrz dziecka w tablicy, a następnie zostaną one wstrzyknięte automatycznie, lub wstrzyknąć je osobno za pomocą adnotacji $ inject:

childService.$inject = ["$http", "$cookies", "parentService"]; 
angular.module("app").service("childService ", childService );
 5
Author: Tiberiu Oprea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-18 10:21:35