2017-09-23 6 views
0

서버에서 데이터를 가져 오는 서비스를 만들었습니다. 브라우저 도구는 데이터가 올바르게 선택되었는지 확인합니다.angular.js 서비스의 데이터를 컨트롤러에 포함시키는 방법은 무엇입니까?

angular. 
    module('karassApp'). 
    factory('Person', ['$rootScope', '$http', function($rootScope, $http){ 

    var persons = []; 
    var loaded = false; 

    // returns a promise that resolves to the persons. 
    var load = function(){ 
     return $http.get('/get_persons').then(function(response){ 
     persons = response.data.map(function(person){ 
      return { 
      id: person.id, 
      fullname: person.fullname, 
      birthdate: person.birthdate ? new Date(person.birthdate) : null, 
      deathdate: person.deathdate ? new Date(person.deathdate) : null, 
      description: person.description, 
      picture: person.picture ? person.picture : '/client/views/person.png' 
      }; 
     }); 

     $rootScope.$broadcast('Persons.update'); 
     loaded = true; 

     return persons; 
     }); 
    }; 

    return { 
     load: load, 
     persons: persons 
    }; 
    }]); 

다음으로 컨트롤러를 사용 중이므로 서비스가 필요합니다.

angular. 
    module('karassApp'). 
    component('personList', { 
    templateUrl: 'client/views/person-list.template.html', 
    controller: ['$scope', 'Person', function PersonListController($scope, Person){ 
     var self = this; 

     Person.load().then(function(){ 
     $scope.persons = Person.persons; 
     }); 
... 

이 시점에서 코드는 실패하고 $ scope.persons는 비어있게됩니다. 나는 그 사람이 데이터를 사람에게 읽어들이도록해야한다는 결심을 기다리고 있습니다. 나는 또한 서비스가 싱글 톤 (singleton)이라고 생각했다. 즉, Person.load()의 첫 번째 호출 이후에 person 변수가 채워 져야 함을 의미한다. 사전에

감사합니다, 조쉬

내가 대답에서 코드를 통합했는데, 지금과 같이 보입니다 업데이트 :

angular. 
    module('karassApp'). 
    factory('Person', ['$http', '$q', function($http, $q){ 

    var persons = []; 

    // returns a promise that resolves to the persons. 
    var load = function(){ 
     return $q(function(resolve, reject){ 
     $http.get('/get_persons').then(function(response){ 
      persons = response.data.map(function(person){ 
      return { 
       id: person.id, 
       fullname: person.fullname, 
       birthdate: person.birthdate ? new Date(person.birthdate) : null, 
       deathdate: person.deathdate ? new Date(person.deathdate) : null, 
       description: person.description, 
       picture: person.picture ? person.picture : '/client/views/person.png' 
      }; 
      }); 
      resolve(persons); 
     }); 
     }); 
    }; 

...

+0

내가 코드를 시도했지만 불행히도 그것은 여전히 ​​작동하지 않았다. –

+0

업데이트는 [지연된 안티 패턴] (https://stackoverflow.com/questions/30750207/is-this-a-ferfer-antipattern)이므로 피해야합니다. $ http 요청이 실패 할 경우 작성한대로 약속이 작성됩니다. 오류 케이스가 제대로 처리되지 않습니다. – georgeawg

답변

1

I 그것을 알아 내었다. 나는 올바른 생각을 가지고 있었지만, 사람들을 돌려 보내서 다음 then에 그것을 넘겨 줄 필요가있었습니다.

서비스 :

angular. 
    module('karassApp'). 
    factory('Person', ['$rootScope', '$http', '$q', function($rootScope, $http, $q){ 

    var persons = []; 

    // returns a promise that resolves to the persons. 
    var load = function(){ 
     return $http.get('/get_persons').then(function(response){ 
     persons = response.data.map(function(person){ 
      return { 
      id: person.id, 
      fullname: person.fullname, 
      birthdate: person.birthdate ? new Date(person.birthdate) : null, 
      deathdate: person.deathdate ? new Date(person.deathdate) : null, 
      description: person.description, 
      picture: person.picture ? person.picture : '/client/views/person.png' 
      }; 
     }); 
     return persons; 
     }); 
    }; 

컨트롤러 :

angular. 
    module('karassApp'). 
    component('personList', { 
    templateUrl: 'client/views/person-list.template.html', 
    controller: ['$scope', 'Person', function PersonListController($scope, Person){ 
     var self = this; 

     Person.load().then(function(persons){ 
     self.persons = persons; 
     }); 
+0

정답입니다. 문제는'.then' 메쏘드의 콜백 함수가'persons'으로 수정 한 인수를 생략했다는 것입니다. – georgeawg