[英]AngularJS Display JSON Data
我正在學習AngularJS並且已經設置了項目的結構,但是當我調用返回JSON的API時,我無法在html中顯示它。
您的想法是單擊按鈕,返回的結果將顯示在{{answer}}中 。
HTML:
<div ng-app="xileapp">
<div ng-controller="searchController">
<input type="button" ng-click="search()" value="search" />
<div>Answer: {{answer}}</div>
</div>
</div>
控制器:
xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) {
$scope.search = function () {
$scope.answer = personSearch.findPlayer();
}
}]);
服務:
xile.service('personSearch', function ($http) {
this.findPlayer = function() {
$http({
method: 'GET',
url: 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Crucify?api_key=222015c4-0898-4f6b-a7d5-2a23c3e0344d'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return response;
});
};
});
URL正在響應成功。 我現在如何獲取要在HTML中顯示的數據。
一旦你有了json,Angular有一個Json過濾器可以添加到實際的綁定表達式中。
{{ answer | json }}
如果需要響應中的實際json,可以在響應對象的data
屬性中找到它。
response.data
改進建議:
我還為你的http
get方法提供了一個'更好'的短手,我覺得它實際上更好,因為它會處理任何被拋出的異常,而不是在你的情況下使用錯誤回調。
return $http.get(apiUrl)
.then(successCB)
.catch(errorCB);
您沒有為answer
分配任何數據(實際上分配undefined
),因為findPlayer
不返回任何內容。
首先,您需要創建服務方法返回promise對象:
this.findPlayer = function() {
var url = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Crucify?api_key=222015c4-0898-4f6b-a7d5-2a23c3e0344d';
return $http({
method: 'GET',
url: url
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return response;
});
};
然后在控制器中使用它:
$scope.search = function () {
personSearch.findPlayer().then(function(data) {
$scope.answer = data;
});
}
請記錄此JSON對象並確定要顯示的比例
{answer: "a"}
然后你的觀點將是
<div>Answer: {{answer.answer}}</div>
並從findPlayer函數或promise返回數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.