【问题标题】:Using $http in AngularJS + WebAPI在 AngularJS + WebAPI 中使用 $http
【发布时间】:2017-04-15 22:33:41
【问题描述】:

我正在尝试在 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

【问题讨论】:

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


    【解决方案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;
        }
      });
    }
    

    【讨论】:

    • 谢谢! CORS 也存在问题。在遵循本主题中的建议后,我也进行了配置,一切正常。
    【解决方案2】:

    您没有将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”消息
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多