2017-08-15 25 views
2

PHPファイルから犬の品種リストを返すファクトリを作成していますが、コントローラに応答データを返すことはできません。私は工場HTTPリクエスト後に工場からコントローラにデータを返すAngularJS

angular.module('myApp') 
    .factory('DataService, function($http) { 
     return { 
      get_breeds: function() { 
       method: 'GET', 
       url: 'http://localhost:8080/php/api/getbreeds.php' 
      }).then(function onSuccess(response) { 
       console.log(response); // responds with 200 
       return response.data; 
      }).catch(function onError(err) { 
       console.log(err); 
      }) 
     } 
    } 
}); 

としてこれを持っており、これが私のコンポーネント

angular.module('myApp') 
    .component('homeComponent', { 
    templateUrl: 'home.component.html, 
    controller: function (DataService) { 

     DataService.get_breeds() 
      .then(function(response) { 
       var dog_breeds = response; 
       console.log(dog_breeds) 
      }); 
    ... 

の一部であり、しかし、私は戻っ何でも、エラーメッセージが届きません。誰かが正しい方向に私を導くことができますか?

+0

誤ってコピーして貼り付けた場合はわかりませんが、この行は 'templateUrl: 'home.component .html、 'は閉じた一重引用符がありません – user2340824

+0

Ahhhええ、それは悪いc&pエラーでした! –

+0

'getBreeds'で' Promise'を返すことを意味しましたか?関数が正しく表示されない場合は、シンタックスハイライトも混乱します。または、 'getBreeds'に' $ http'を注入した場所はどこですか? – sabithpocker

答えて

0

はちょうど私が私が質問を投稿しませずっと後にそれを考え出し

angular.module('myApp') 
    .factory('DataService, function($http) { 
     var service = this;  
     service.get_breeds = function() { 
      return $http.get('http://localhost:8080/php/api/getbreeds.php') 
     } 
    } 
}); 
+0

投稿してからずっとこのことを理解しました!最後に私はこれを思いついた: angular.module( 'myApp') –

1

サービスからのHTTPリクエストを返します!

最後に、私はちょうどURLからデータを返さ工場製:

angular.module('myApp') 
    .factory('DataService', function($http) { 
     return { 
      get_dog_breeds: function(urlString) { 
       return $http.get(urlString) 
     } 
    } 
}) 

をそしてそのように私のコンポーネントのコントローラでそれを呼ばれる:

DataService.dog_breeds('http://localhost:8080/php/api/getbreeds.php') 
      .then(function (response) { 
       console.log(response.data); 
       $scope.dog_breeds = response.data; 
       return $scope.dog_breeds; 
      }).catch(function (error) { 
      console.log('Error returned: ' + error 
       + ' Please make sure the service you\'re trying to use exists'); 
      return false; 
     }); 

そして、それだけで働いていました!

愛するAngularJSこれまでところでみんな:)

0

それは

使用これはあなたの工場で

angular.module('myApp') 
.factory('DataService', function($http) { 
    return { 
     get_breeds: function() { 
      var request = $http({ 
      method: 'GET',        
      url: 'http://localhost:8080/php/api/getbreeds.php' 
     }); 
     return request; 
    } 
} 
}); 

を仕事とデータを取得するために、コントローラでこれを使用する必要があり、これをやってみ

DataService.get_breeds() 
    .then(function(response){ 
     console.log(response.data); 
}); 
関連する問題