简体   繁体   中英

Using $http in AngularJS + WebAPI

I am trying to print out list of categories using AngularJS on top of WebAPI. I have the following page and when I navigate to it, I get alert message containing "-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? In specific, for an external API call? and here AngularJS not displaying API data

You did't inject the categoriesService into your controller, but instead injected a 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;
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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