AngularJS显示JSON数据

Ben*_*rke 9 html javascript json angularjs

我正在学习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>
Run Code Online (Sandbox Code Playgroud)

控制器:

xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) {

    $scope.search = function () {

        $scope.answer = personSearch.findPlayer();

    }

}]);
Run Code Online (Sandbox Code Playgroud)

服务:

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;

        });

    };

});
Run Code Online (Sandbox Code Playgroud)

URL正在响应成功.我现在如何获取要在HTML中显示的数据.

The*_*hap 6

一旦你有了json,Angular有一个Json过滤器可以添加到实际的绑定表达式中.

{{ answer | json }}
Run Code Online (Sandbox Code Playgroud)

如果你想从响应中获得实际的json,你可以data在响应对象的属性中找到它.

response.data
Run Code Online (Sandbox Code Playgroud)

改进建议:

我还为你的httpget方法提供了一个'更好'的短手,我觉得它实际上更好,因为它会处理任何被抛出的异常,而不是在你的情况下使用错误回调.

return $http.get(apiUrl)
          .then(successCB)
          .catch(errorCB);
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 4

您没有将任何数据分配给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;
    });
};
Run Code Online (Sandbox Code Playgroud)

然后在控制器中使用它:

$scope.search = function () {
    personSearch.findPlayer().then(function(data) {
        $scope.answer = data;
    });
}
Run Code Online (Sandbox Code Playgroud)