2017-08-15 41 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

啊啊,這是一個錯誤的C&P錯誤! –

+0

您是否想要在'getBreeds'中返回'Promise'?該功能看起來不正確,語法熒光筆也困惑。或者你在'getBreeds'中使用注入'$ http'的地方? – sabithpocker

回答

0

單從服務返回的HTTP請求

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

我想通了沒多久,我張貼的問題!

最後我做了一個工廠,只是從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); 
}); 
相關問題