我正在尝试使用AngularJS在WebAPI上打印出类别列表。我有以下页面,当我导航至该页面时,会收到包含“ -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>
我究竟做错了什么?我从这里尝试了一些示例:如何在AngularJS中正确使用HTTP.GET?具体来说,是否需要外部API调用?这里AngularJS不显示API数据
您的服务返回了一个承诺,但是当该承诺得到解决时,将不会返回任何数据:
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;
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句