首页 > 解决方案 > Angular 从 json api 返回空白 response.data

问题描述

ng-repeat 返回空白,我是 Angular 的新手。我检查了错误,但没有发现。我真的不知道这里有什么问题。

(function() {

  var app = angular.module("testApp", []);

  app.controller("MainController", function($scope, $http) {
   $scope.search = function(username) {
  $http.get("https://api.github.com/users/" + username)
    .then(onUserComplete, onError);

  $http.get($scope.user.repos)
    .then(onRepos, onReposError);
};

var onUserComplete = function(response) {
  $scope.user = response.data;
};

var onRepos = function(response) {
  $scope.repos = reponse.data;
};
  });

}());

下面是 HTML,我想在其中显示 GitHub 上特定用户的存储库:

  <table>
    <thead>
      <tr>
       <th>Name</th>
       <th>Stars</th>
       <th>Language</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="repo in repos">
        <td>{{repo.name}}</td>
        <td>{{repo.stargazers_count }}</td>
        <td>{{repo.language}}</td>
      </tr>
    </tbody>
  </table>

标签: javascriptangularjspromise

解决方案


问题是您正在执行的 HTTP 调用是异步的,因此当您执行第二个调用时,您还没有用户。您必须连接承诺。如果您不打算在任何地方使用用户,仅用于第二次调用,那么您可以简化代码:

$http.get("https://api.github.com/users/" + username)
     .then(function(response) {
         return $http.get(response.data.repos_url);
     })
     .then(function(response) {
         $scope.repos = reponse.data;
     }, 
     onError);

第一个then在第一次get成功时执行,所以我调用第二个get。然后当第二个 HTTP 调用成功时执行第二个then 。通过这种方式,我们将两个 Promise 连接起来。

我在JSFiddle写了一个完整的例子。

但是我在这里复制了完整的代码,所以它可能对其他人有用:

AngularJS

var myModule = angular.module('myModule', []);

myModule.controller('myController', ['$http', function ($http) {
    var $ctrl = this;
    $ctrl.username = null;
    $ctrl.repos = null;


    $ctrl.getRepositoryData = function () {   
        $ctrl.repos = null;
        $http.get('https://api.github.com/users/' + $ctrl.username)
             .then(function(response) {
                 return $http.get(response.data.repos_url);
             })
             .then(function(response) {
                 $ctrl.repos = response.data;
             }, 
             function (error) {
                 console.log('Error happened:', error);
             });
    };
}]);

HTML

<div ng-app="myModule">
    <div ng-controller="myController as ctrl">
        <div>
            <input type="text" ng-model="ctrl.username"/>
            <button type="button" ng-click="ctrl.getRepositoryData()">
                Get Repos
            </button>
            <p>User repositories: {{ctrl.repos}}</p>
        </div>
   </div>
</div>

推荐阅读