2016-04-28 17 views
2

は、サービスからコントローラ内のデータを取得できません

app.service('customersService', function ($http) { 
 
    this.getCustomer = function (id) { 
 
     $http({ 
 
      method: 'GET', 
 
      url: '/getCustomer', 
 
      params: {id: id}, 
 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
 
     }).success(function(data) { 
 
      console.log(data); 
 
      return data; 
 
     }) 
 
    }; 
 
});

私はこの

customersService.getCustomer(customerID).then 
を実行しようとするサービス このコードの問題から、コントローラ内のデータをされて得ることができません

angular.js:13294 TypeError: Cannot read property 'then' of undefined.

主なものは、サービスへの呼び出しが生成され、サービス内のコンソールに結果を表示しようとすると、データがそこにあります。しかし、私は私のコントローラでデータを取得することはできません。

答えて

2

あなたは$http GET要求から約束を返すされていませんbecuaseあなたはそのエラーを取得します。

このような編集コードを:

app.service('customersService', function ($http) { 
    this.getCustomer = function (id) { 
     return $http({ 
      method: 'GET', 
      url: '/getCustomer', 
      params: {id: id}, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
     }); 
    }; 
}); 

そして、あなたのコントローラで.then()で、あなたは応答データを扱います。

app.controller('myController', function($scope, customerService){ 

    customersService.getCustomer(customerID) 
     .then(function(response){ 
     $scope.data = response; 
     }) 
}) 
+0

現在かなりうまく動作しています。ありがとう! –

0

あなたは$ http約束を返すことを忘れています。その理由はundefinedが返されます。あなたは次のことを実行する必要があります。

... 
return $http({ ... 
0

与えられたコードを試してください。

app.service('customersService', function ($http) { 
    var getCustomer = function (id) { 
     return $http({ 
      method: 'GET', 
      url: '/getCustomer', 
      params: {id: id}, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
     }) 
    }; 

    var customersService = { 
      getCustomer: getCustomer 
    } 
    return ProfileService; 

}); 
関連する問題