Javascript HTTP请求AngularJS后将数据从工厂返回控制器
我正在编写一个工厂,它从一个php文件返回一个狗品种列表,但是我不能将响应数据返回给我的控制器。我把它当作一个工厂Javascript HTTP请求AngularJS后将数据从工厂返回控制器,javascript,angularjs,Javascript,Angularjs,我正在编写一个工厂,它从一个php文件返回一个狗品种列表,但是我不能将响应数据返回给我的控制器。我把它当作一个工厂 angular.module('myApp') .factory('DataService, function($http) { return { get_breeds: function() { method: 'GET', url: 'http://localhost
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)
});
...
但我没有收到任何返回的内容和错误消息。有人能指引我正确的方向吗 只需从服务返回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')
}
}
});
我在贴出问题后不久就明白了 最后,我创建了一个工厂,它刚刚从URL返回了数据:
angular.module('myApp')
.factory('DataService', function($http) {
return {
get_dog_breeds: function(urlString) {
return $http.get(urlString)
}
}
})
然后在我的组件的控制器中调用它,如下所示:
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到目前为止顺便说一句,伙计们:)试着这样做吧,应该行得通 在你的工厂里使用这个
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);
});
不确定是否复制和粘贴错误,但这一行
templateUrl:'home.component.html,
缺少一个结束单引号是的,这是一个严重的c&p错误!您的意思是在getbrides
中返回承诺吗?函数看起来不正确,语法高亮也很混乱。或者你在哪里使用注入的$http
在getbrides
中?你没有在代码中调用$http。我在发布后不久就发现了这一点!最后我想到了这个:angular.module('myApp')