2016-12-01 80 views
0

我想在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

回答

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

謝謝! CORS還存在一個問題。在遵循這個主題的建議之後,我也配置了這一點,並且一切正常。 – eXPerience

1

你我以前不注入categoriesService到控制器中,而是注入了dataService。試試這個

myApp.controller('CategoriesCtrl', function ($scope, categoriesService) { 
     $scope.data = null; 
     categoriesService.getData().then(function (response) { 
      $scope.data = response; 
     }, function (response) { 
      alert(response.status); 
     }); 
    }); 
+0

非常感謝頭了!但結果仍然一樣,警報與「-1」消息 – eXPerience

相關問題