JSON Information for AngularJS

I am learning AngularJS and have a project structure, but when I call an API that returns JSON to me, I cannot display this in html.

The idea is that you press the button and the returned result will be displayed in {{answer}}.

HTML:

<div ng-app="xileapp"> <div ng-controller="searchController"> <input type="button" ng-click="search()" value="search" /> <div>Answer: {{answer}}</div> </div> </div> 

Controller:

 xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) { $scope.search = function () { $scope.answer = personSearch.findPlayer(); } }]); 

Services:

 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; }); }; }); 

The url strikes with the correct answer. How do I now get the data to display in HTML.

+6
source share
3 answers

You don't assign answer data (actually assigning undefined ) because findPlayer nothing.

So, first of all, you need to make a method return method method:

 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; }); }; 

then consume it in the controller:

 $scope.search = function () { personSearch.findPlayer().then(function(data) { $scope.answer = data; }); } 
+4
source

Angular has a Json filter that you can add to the actual binding declaration as soon as you return json.

 {{ answer | json }} 

If you want the actual json from the response, you can find it in the data property of the response object.

 response.data 

Improvement recommendation:

I also suggested the β€œbest” short hand for your http get method, which, in my opinion, is better because it will handle any exceptions that are thrown and not use the error callback in your case.

 return $http.get(apiUrl) .then(successCB) .catch(errorCB); 
+5
source

Please register this JSON object and determine the proportion you want to display

 {answer: "a"} 

then your opinion will look like

 <div>Answer: {{answer.answer}}</div> 

and return data from findPlayer or promise

+1
source

All Articles