我正在学习AngularJS并且已经设置了项目的结构,但是当我调用返回JSON的API时,我无法在html中显示它.
您的想法是单击按钮,返回的结果将显示在{{answer}}中.
HTML:
Answer: {{answer}}
控制器:
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);