javascript - 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>
解决方案
问题是您正在执行的 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>
推荐阅读
- android - Kotlin 覆盖 WebView
- spring - 如果为空,JPA 避免子集合初始化
- r - dfidx 和 mlogit.data 为选择模型的预测提供不同的输出
- node.js - 如何使用 Vuejs 从本地目录导入“.xlsx”而不使用“type=file”进行覆盖
- xaml - Xamarin.Forms.Shell:是否可以将自定义 NavigationPage 与 Shell 一起使用?
- swift - Xcode 分发失败并出现错误:框架未包含在正确命名的目录中。它应该在“框架”下
- prolog - Prolog 中的逻辑
- python - 似乎无法让海龟图形在 VsCode 上工作
- django - 在 django ORM 中以这种方式访问对象时会有任何性能改进吗?
- java - 如何在java中创建字典