简体   繁体   English

在AngularJS + WebAPI中使用$ http

[英]Using $http in AngularJS + WebAPI

I am trying to print out list of categories using AngularJS on top of WebAPI. 我正在尝试使用AngularJS在WebAPI上打印类别列表。 I have the following page and when I navigate to it, I get alert message containing "-1". 我有以下页面,当我导航至该页面时,会收到包含“ -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? 我从这里尝试了以下示例: 如何在AngularJS中正确使用HTTP.GET? In specific, for an external API call? 具体来说,是否需要外部API调用? and here AngularJS not displaying API data 这里AngularJS不显示API数据

You did't inject the categoriesService into your controller, but instead injected a dataService . 你我以前不注入categoriesService到控制器中,而是注入了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);
        });
    });

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM