2014-10-22 5 views
-1

각도 JS로 시작하고 학생 데이터가있는 팩토리를 만들었습니다. 학생 데이터는 다음과 같습니다. 내 데이터 객체에 추가 할 성공에로드되는 데이터를 어떻게 얻을 수있다 해결할 수없는 어떤

.factory('Students', ['$http', function($http) { 
     var data = {}; 
     return { 
      getStudents: function() { 
       $http.get('api/students.json'). 
       success(function(data, status, headers, config) { 
       console.log(data.male); //returns the array of males 
       data.studentlist = data.male; 
       data.propertyOne = 'propertyOne'; //returns propertyOne but should also return in console.log(data) that I have further down the page. 
       console.log(data.propertyOne); 

       }). 
       error(function(data, status, headers, config) { 
       // log error 
       console.log('error'); 
       }); 
       data.propertyTwo = 'propertyTwo'; 
       console.log(data); //returns propertyTwo 

       return data; 
      } 
     } 
    }]); 

    .controller('StudentCtrl', ['$scope', 'Students', 
     function ($scope, Students) { 
     $scope.students = Students.getStudents(); 
     console.log($scope); // only properyTwo is returned in the students scope 
    }]) 

아래와 같이

{ 
    "male": [ 
     ["John", "Smith", "2000-10-10"], 
     ["James", "Smith", "2000-10-10"] 
    ] 
} 

나는 공장과 컨트롤러 설정을 가지고? 내 의견에서 알 수 있듯이 내 성공으로 데이터를 반환하지만 내 성공 함수 밖에서는 더 이상 사용할 수 없습니까? 내 컨트롤러에서 students.json 파일에서 반환 된 학생 목록에 액세스 할 수 있도록이 작업을 수행하려면 여기를 변경해야합니까?

+1

일부 다른 사람들이 여기에, 이들 중 다수가 있습니다 ... HTTP :. // 유래. com/questions/12505760/processing-http-response-in-service, http://stackoverflow.com/questions/19121918/returning-response-data-from-http-in-angular-factory 공식 문서는 잘. – PSL

답변

2

타이밍 문제입니다. console.log(data); //returns propertyTwo이 실행되면 아직 성공 콜백에서 과제를 수행하지 못했습니다. 타이밍이 중요하다면 둘 다 성공 콜백으로 옮겨야합니다.

나는 당신이 (컨트롤러의 약속을 해결 서비스에서 그 일을 대신이 성공 콜백을 추가하는 것이 좋습니다 것입니다

관련 문제