[英]Using $http in AngularJS + WebAPI
我正在嘗試使用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數據
你我以前不注入categoriesService
到控制器中,而是注入了dataService
。 嘗試這個
myApp.controller('CategoriesCtrl', function ($scope, categoriesService) {
$scope.data = null;
categoriesService.getData().then(function (response) {
$scope.data = response;
}, function (response) {
alert(response.status);
});
});
您的服務返回一個承諾,但是當該承諾解決時,不會返回任何數據:
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;
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.