Angularjs Service http

Asked

Viewed 529 times

0

I have a service at the angle and wanted to do a foreach to recover the user value, 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’t do this foreach, I can never buy the values, I don’t know if it’s the return of the api, or value.name isn’t getting any value.

my json returns this:

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

Anyone can help?

  • Try to get only the result and not result.data, from a console.log(result); and see the output.

  • I gave a console log outside the $http block and came empty :( " [] " Inside the $http block came like this: Object {data: Array[1], status: 200, config: Object}

  • Dude is returning ok, what is the result content.data? Have that data there. And that’s right you have to run this in the callback of http.get, did you ever see the "date" content in "result"? if not there, you have to see what is coming in the function parameter that "user".

1 answer

1


Use your foreach inside the callback .then(function(resultado){})

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

 .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 problems:

.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');
         }
      })
    });
  }
}
  • https://scotch.io/tutorials/declaring-angularjs-modules-for-minification

Browser other questions tagged

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