Injection of dependency into service

Asked

Viewed 149 times

2

Guys I can do dependency injection in services? for example, I tried this:

service 1

var crypto = angular.module('crypto',['ngRoute']);

service 2

var teste = angular.module('userlog',['crypto']);
teste.service('userlogService','cryptoService', function (cryptoService) {

but it’s making a mistake

1 answer

1

In service, it works differently:

var teste = angular.module('userlog',['crypto']);

teste.service('seuService', ['userlogService','cryptoService', function (userlogService, cryptoService) {
//aqui o serviço
}]);

If you won’t use elsewhere, you can also do so only:

  teste.service('seuService', function (userlogService, cryptoService) {
    //aqui o serviço
    });

If you plan to use multiple methods within the same service, I recommend that you use a Factory instead of a service:

 var teste = angular.module('userlog',['crypto']);

 teste.factory('seuService', function () {

      function seuService() {

          var userlogService = function(scope) {
          //service 1
          };

          var cryptoService = function(scope) {
          //service 2
          }; 
      }
      return new seuService(); 
    });

Using the controller would be something like this:

teste.controller('seuController',['seuService',function(seuService) {
    seuService().userlogService($scope);
    seuService().cryptoService($scope);
}]);
  • I don’t know if I understand it correctly, but my idea is to make modules in different files, work modularly type: moduleDecurity>(depends)moduloDeLoginDeUsuario>(depends)moduloDeConnection. reusing functions within services and controllers, similar to java, where the class is cared for, an instance is created and the methods of the imported class are used

  • You can, even should say (should), work modularly, however, when your module only pertains to one type of use, such as user login, it makes a lot of sense to segment your system when it will not be used outside of the same scope. Just a suggestion.

  • the login module would be to check not only the login authorization, but also to use the services, type it will have to be present all the time, understand?

  • Okay, but you got it right...

  • more or less kk I am new to the parade, I have to learn in the race, and I have a little difficulty in reusing codes of the modules

Browser other questions tagged

You are not signed in. Login or sign up in order to post.