Reputation: 466
I am trying to print out list of categories using AngularJS on top of WebAPI. I have the following page and when I navigate to it, I get alert message containing "-1".
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/angular.min.js"></script>
<script language="javascript">
var myApp = angular.module('myApp', []);
myApp.service('categoriesService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function () {
// $http() returns a $promise that we can add handlers with
.then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/categories'
});
}
});
myApp.controller('CategoriesCtrl', function ($scope, categoriesService) {
$scope.data = null;
categoriesService.getData().then(function (response) {
$scope.data = response;
}, function (response) {
alert(response.status);
});
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="CategoriesCtrl">
<ul>
<li ng-repeat="category in data">
{{ category.Name }}
</li>
</ul>
</div>
</body>
</html>
What am I doing wrong? I tried samples from here: How to use HTTP.GET in AngularJS correctly? In specific, for an external API call? and here AngularJS not displaying API data
Upvotes: 0
Views: 87
Reputation: 4360
Your service returns a promise but when the promise resolves no data is returned:
this.getData = function () {
return $http.get('https://www.example.com/api/categories').then(
function(response) {
console.log(response);
return response;
},
function(error) {
console.log(error);
return error;
}
});
}
Upvotes: 1
Reputation: 68685
You did't inject the categoriesService
into your controller, but instead injected a dataService
. Try this
myApp.controller('CategoriesCtrl', function ($scope, categoriesService) {
$scope.data = null;
categoriesService.getData().then(function (response) {
$scope.data = response;
}, function (response) {
alert(response.status);
});
});
Upvotes: 1