AngularJS Service http

0

I have a service in the angle and wanted to make a forEach to retrieve the value of the user, to authenticate the login

My service:

.service('usuariosService', function ($rootScope, $location,$http) {

    this.validaLogin = function(user){
        var usuarios = [];
$http.get('api/user').then(function(resultado){
              usuarios = resultado.data;
          });

        angular.forEach(usuarios, function(value, index){            
                if(value.nome == user.username){
                    $rootScope.usuarioLogado = value;
                }else{
                    console.log('Não é igual');
                }
            })
    }
})

But I can not do this forEach, I can never buy the values, I do not know if it's the api return, or the value.name is not getting any value.

My json returns this:

[{ "nome" : "teste", "password" : "teste" },
 { "nome" : "teste1", "password" : "teste1" }];

Can anyone help?

    
asked by anonymous 20.05.2016 / 01:05

1 answer

1

Use your forEach within the callback .then(function(resultado){})

When the angular.forEach is called, not necessarily the value of usuarios will be the return of the $ http request, however within the callback this value is guaranteed.

 .service('usuariosService', function($rootScope, $location, $http) {
    this.validaLogin = function(user) {
      $http.get('api/user').then(function(resultado) {

        angular.forEach(resultado.data, function(value, index) {
         if (value.nome == user.username) {
           $rootScope.usuarioLogado = value;
         }else {
            console.log('Não é igual');
         }
      })
    });
  }
})

I also recommend changing the code to avoid minification issues:

.service('usuariosService', usuariosService);

usuariosService.$inject = ['$rootScope','$location','$http'];    

function usuariosService($rootScope, $location, $http) {
    this.validaLogin = function(user) {
      $http.get('api/user').then(function(resultado) {

        angular.forEach(resultado.data, function(value, index) {
         if (value.nome == user.username) {
           $rootScope.usuarioLogado = value;
         }else {
            console.log('Não é igual');
         }
      })
    });
  }
}
    
20.05.2016 / 16:12