eXPerience eXPerience - 1 year ago 115
AngularJS Question

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>
<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
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) {
<body ng-app="myApp">
<div ng-controller="CategoriesCtrl">
<li ng-repeat="category in data">
{{ category.Name }}

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

gyc gyc
Answer Source

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) {
      return response;
    function(error) {
      return error;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download