2016-08-17 4 views
-2
services.factory('profilFactory',['$q','$http',function($q,$http){ 
    var factory2 = 
    { 
     profils : {}, 
     getProfils : function(){ 
      $dfd = $q.defer(); 
      $http.get('data.json') 
       .success(function(data,status){ 
        this.profils = data.profil; 
        $dfd.resolve(this.profils); 
       }) 
       .error(function(data,status) { 
        $dfd.reject('erreur recuperation des profils'); 
       }); 
      return $dfd.promise; 
     }, 
     getProfil : function(idProfil){ 
      var profil={}; 
      var profils = {}; 
      factory2.getProfils().then(function(data){ 
       profils= data; 
       console.log(profils);//all right until here profils has values 
      }); 
      console.log(profils);// now profils is empty :\ and the foreach will not execute 
      angular.forEach(profils, function(value, key){ 
       if(value.id == idProfil){ 
        profil= value; 
       } 
      }); 
      return profil; 
     } 

    }; 
    return factory2; 
}]); 

Это скриншот проблемы: метод «getProfil» this is a screenshot of the problem : method "getProfil"Почему переменные остаются пустыми на заводских угловых?

+0

Добро пожаловать в StackOverflow. Пожалуйста, разместите свой код здесь в вопросе и добавьте дополнительную информацию, чтобы объяснить проблему. –

ответ

0

Чтобы ответить на ваш вопрос: «Почему переменные пустые на заводе», это потому, что вы используете оператор console.log в том месте, где данные еще не загружены с сервера. Чтобы узнать больше, Google это: «angularjs http get promises»

services.factory('profilFactory',['$q','$http',function($q,$http){ 
    var factory2 = 
    { 
     profils : {}, 
     getProfils : function(){ 
      $dfd = $q.defer(); 
      $http.get('data.json') 
       .success(function(data,status){ 
        this.profils = data.profil; 
        $dfd.resolve(this.profils); 
       }) 
       .error(function(data,status) { 
        $dfd.reject('erreur recuperation des profils'); 
       }); 
      return $dfd.promise; 
     }, 
     getProfil : function(idProfil){ 
      var profil={}; 
      var profils = {}; 
      // Run a function to get data, "THEN" we run a function to process the data: 
      factory2.getProfils().then(function(data){ 
       // Data has now been loaded so we can process it and return it. 
       profils = data; 
       angular.forEach(profils, function(value, key){ 
        if(value.id == idProfil){ 
         profil= value; 
        } 
       }); 
       return profil; 
      }); 

      console.log(profils); // This is EMPTY because it runs immediately after 
      // the factory2.getProfils() function which may need several seconds to 
      // load data. That's why "profils" is empty. The data hasn't loaded at 
      // this point. 
      // 
      // No data will be available at this level of the code. Don't try to access 
      // "profils" here! Only in your .then() function above. 
     } 

    }; 
    return factory2; 
}]); 
0

Ваше console.log заявление находится вне обратного вызова. Это проблема. Вам нужно console.log в обратном вызове или использовать наблюдателя, чтобы обновить его, когда он будет изменен. Для справок в будущем вы всегда должны копировать и вставлять свой код здесь.

+0

Я хочу, чтобы objet ** profils ** сохранял значение, потому что если нет, то foreach не выполнит, может ли помочь мне. –

Смежные вопросы