在AngularJS + WebAPI中使用$ http

时间:2016-12-01 10:23:58

标签: javascript angularjs asp.net-web-api

我试图在WebAPI上使用AngularJS打印出类别列表。我有以下页面,当我导航到它时,我得到包含“-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>

我做错了什么?我从这里试过样品: How to use HTTP.GET in AngularJS correctly? In specific, for an external API call? 和这里 AngularJS not displaying API data

2 个答案:

答案 0 :(得分:1)

您没有将categoriesService注入您的控制器,而是注入dataService。试试这个

myApp.controller('CategoriesCtrl', function ($scope, categoriesService) {
        $scope.data = null;
        categoriesService.getData().then(function (response) {
            $scope.data = response;
        }, function (response) {
            alert(response.status);
        });
    });

答案 1 :(得分:1)

您的服务会返回一个承诺,但是当承诺解决时,不会返回任何数据:

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