2016-12-01 6 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を注入did't、代わりに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

関連する問題