2016-12-09 1 views
0

HTTP 요청으로 구성 요소에 데이터를 설정하고 싶지만 $ http.get 외부 데이터는 정의되지 않습니다.AngularJS에서 response.data 값에 액세스하는 방법은 무엇입니까?

$ http.get 외부의 응답 데이터를 얻는 방법은 무엇입니까?

'use strict'; 
angular. 
module('filesApp'). 
component('filesList', { 
    template: 
     '<ul>' + 
     '<li ng-repeat="file in $ctrl.files">' + 
      '<span>{{file.data1}}</span>' + 
      '<p><a href="{{file.data2}}">Create</a></p>' +    
     '</li>' + 
     '</ul>',  
    controller: function FilesListController($http, $scope) { 
     //need response.data here 
       $http.get('/api/1').then(function (response) { 
       if (response.data.error) { 
        return null; 
       } else {      
        $http.get('/api/2' + response.data).then(function (response) { 
         if (response.data.error) { 
          return null; 
         } else {        
          //response.data contains data that I need.        
          return response.data; 
         } 
        }); 
       } 
      });   
    } 
}); 
+0

스토어는 한 번 $ http.get 경우 당신이 그것을 사용하려고 처음 $ http.get – ocespedes

답변

3

범위에 response.data을 저장해야보기에 사용할 수 있습니다. 범위에서

'use strict'; 
angular.module('filesApp') 
    .component('filesList', { 
     template: 
      '<ul>' + 
       '<li ng-repeat="file in $ctrl.files">' + 
        '<span>{{file.data1}}</span>' + 
        '<p><a href="{{file.data2}}">Create</a></p>' +    
       '</li>' + 
      '</ul>',  
     controller: function FilesListController($http, $scope) { 
       $http.get('/api/1').then(function (firstResponse) { 
        if (firstResponse.data.error) { 
         return null; 
        } else {      
         $http.get('/api/2' + firstResponse.data).then(function (secondResponse) { 
          if (secondResponse.data.error) { 
           return null; 
          } else { 
           $scope.files = secondResponse.data; 
          } 
        }); 
       } 
      });   
     } 
}); 
+0

$ scope.files에서 사용할 수 있도록, 수행? –

+0

외부에서 정의되지는 구성 요소 – Sophie

0

이렇게하는 방법에는 여러 가지가 있습니다. 가장 간단한 방법은 응답 데이터를 범위의 변수에 저장하는 것입니다. 예 :

controller: function FilesListController($http, $scope) { 
    //need response.data here 
    $http.get('/api/1').then(function (response) { 
     if (response.data.error) { 
      return null; 
     } else {      
      $http.get('/api/2' + response.data).then(function (response) { 
       if (response.data.error) { 
        return null; 
       } else {        
        //response.data contains data that I need. 
        $scope.dataYouNeed = response.data;        
       } 
      }); 
     } 
    });   

}

할 수 있습니다 디스플레이 그것을 어딘가에 {{dataYouNeed}}에보기있다.

관련 문제