Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  10] [ 7]  / answers: 1 / hits: 18713  / 9 Years ago, thu, december 24, 2015, 12:00:00

I am learning AngularJS and have the structure of the project set up but when i call the API that returns me JSON i can't display that in the html.



The idea is you click on 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();

}

}]);


Service:



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 is hitting success with the correct response. How do I now get the data to display in the HTML.


More From » html

 Answers
23

You are not assigning any data to the answer (actually assigning undefined) because findPlayer doesn't return anything.



So first of all, you need to make service method return promise object:



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 controller:



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

[#63953] Tuesday, December 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samarab

Total Points: 620
Total Questions: 95
Total Answers: 89

Location: Bonaire
Member since Wed, May 11, 2022
2 Years ago
;