0

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

2 Answers 2

1

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;
    }
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! There was ALSO an issue with CORS. After following advices in this topic, I configured that as well and everything worked.
1

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

1 Comment

Thanks a lot for the heads up! But the result remains the same, alert with "-1" message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.