我正在编写一个从 php 文件返回狗品种列表的工厂,但我无法将响应数据返回到我的 Controller 。我有这个作为工厂
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)
});
...
但我没有收到任何返回信息和错误消息。有人可以指导我正确的方向吗?
最佳答案
我发布问题后不久就想通了!
最后我做了一个工厂,只从 URL 返回数据:
angular.module('myApp')
.factory('DataService', function($http) {
return {
get_dog_breeds: function(urlString) {
return $http.get(urlString)
}
}
})
然后像这样在我的组件的 Controller 中调用它:
DataService.get_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 顺便说一句 :)
关于javascript - 在 HTTP 请求 AngularJS 之后将数据从工厂返回到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699202/