I’m having trouble reading a service variable on other controllers

Asked

Viewed 61 times

1

I have the following problem:

I have a service where I create a variable that I will manipulate and send to another controller.

This is my service

app.service("maissaude", [
  "$rootScope",
   function($rootScope) {
    $rootScope.nomeMinimo = ""; //Variável que vou manipular e ler em outro controller
}]);

In this same service I have a method that saves a minimum record in the api and returns the saved user:

minimumRegistration: function(form, doctor) {
      maissaude.http.post({
        url: "url que vai na api salvar o dado",
        data: maissaude.signup.modelMinimum,
        callback: {
          success: function(data) {
            var nomeMinimo = data.name;
            $rootScope.nomeMinimo = nomeMinimo;//Atualizo meu nomeMinimo da mesma forma que fiz lá no início do método
            $window.location = "/login/#/cadastro/" + data.id;
          }
        }
      });
}

In another controller I read this $rootScope.nomeMinimo But it doesn’t come with the data that was assigned to it after saving the user, It comes empty the way I declared it up there;

app.controller("CadastroController", [
  "$scope",
  "$rootScope",
  "maissaude",
  function($scope, $rootScope, maissaude) {
    console.log("Variável global!!!!!!!!!!!!!!!!!");
    console.log($rootScope.nomeMinimo);
  }
]);

Someone can tell me what I have to do to be able to read this console, the data I manipulated in the other service. Please!!

  • 1

    Girl, but if you set a service to do this, it should not return an object, rather than a $rootScope?

  • Detail.... This one http.post is an angular lib or is using some other Javascript framework? Make a test by leaving a $watch registered at $rootScope with the value nomeMinimo. Type $rootScope.$watch('nomeMinimo', (v) => console.log(v))

  • Wallace I will return an object, but I need to pass the Minimum data to the customer to finish their registration on another page. I just need to keep the models' names.

  • Ah and I’m using Angularjs

  • 1

    Gabriela, but if you put the value directly on maisservico doesn’t work? Usually I do this at the angle and work smoothly. Example: maisservico.nomeMinimo = data.name

  • If you can access it, you can log in to chat to better explain the problem. I think it would be nice to put the full source of maisservico (of course, if it doesn’t display some sensitive information)

  • 1

    I asked you about the method you use to requisition $http because if it is an external library (read "that is not adapted to the angular")talvez seja necessário executar um$Scope. $apply()depois do$window.Location`

  • Oh got it, I’m trying to use only the most saude.nameMinimo, I even have an isLogin, however it is in the same controller, already this minimum name I want to move from a service to a controller

  • 1
  • 1

    Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

Show 5 more comments

1 answer

1

Use the $rootScope to store a global variable is not a good practice because its variable will be available everywhere in the application without due treatment. You started with the right idea of using a service for this. I’ll leave a simple example of how to share variables using two (or more) controllers.

angular
  .module('minhaApp', []);

// Service para compartilhamento dos dados
angular
  .module('minhaApp')
  .factory('principalService', principalService);

principalService.$inject = [];

function principalService() {
  var service = {
    informacoes: {
      nomeMinimo: ''
    }
  };

  return service;
};

// Controller Primário
angular
  .module('minhaApp')
  .controller('ControllerPrimario', ControllerPrimario);

ControllerPrimario.$inject = ['principalService'];

function ControllerPrimario(principalService) {
  var vm = this;
  vm.informacoes = principalService.informacoes;
}

// Controller Secundário
angular
  .module('minhaApp')
  .controller('ControllerSecundario', ControllerSecundario);

ControllerSecundario.$inject = ['principalService'];

function ControllerSecundario(principalService) {
  var vm = this;
  vm.informacoes = principalService.informacoes;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="minhaApp" style="display:inline-flex">
  <div ng-controller="ControllerPrimario as vm" style="border:solid black">
    <input type="text" ng-model="vm.informacoes.nomeMinimo" />
  </div>
  
  <div ng-controller="ControllerSecundario as vm" style="border:solid black">
    <input type="text" ng-model="vm.informacoes.nomeMinimo" />
  </div>
</div>

You can notice in the example above that I just created an object informacoes with an attribute nomeMinimo in the service. Within the controllers performed the assignment of this attribute to a variable that can be manipulated into within both controllers mirroring this behavior for all contexts.

Browser other questions tagged

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