如何访问 AngularJS 中的 response.data 值?

Ton*_* V. 0 javascript get request angularjs

我想通过 http 请求在我的组件中设置数据,但 $http.get 之外的数据未定义。

如何在 $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;
                      }
                  });
              }
          });          
  }
});
Run Code Online (Sandbox Code Playgroud)

Sop*_*hie 5

您需要存储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;
                          }
                  });
              }
          });          
      }
});
Run Code Online (Sandbox Code Playgroud)