您好,我的代码非常简单,但我无法将 http 结果记录到此:
var app = angular.module('app', ['ngRoute']);
app.run(['contacts_helper','$rootScope', function(contacts_helper,$rootScope){
var x = contacts_helper.getAll();
console.log(x); // returns undefined
}]);
app.service('contacts_helper',['$http','$rootScope', function($http,$rootScope){
this.getAll = function(){
$http({
method:'GET',
url:'http://localhost/myjson.json',
params:{id_user:$rootScope.session.id_user}
}).success(function(response){
return response;
}).error(function(err){
return false;
});
}
}]);
它总是在控制台返回undefined
那么如何实现呢?
最佳答案
在您的界面中 - 您应该使 getAll
成为一个 promise 。您需要使用 .then
来访问它的内容:
contacts_helper.getAll().then(function(response){
console.log(response);
}]);
这是可能的,通过更改 getAll
以返回 http 调用。
this.getAll = function(){
return $http({
method:'GET',
url:'http://facebook.com',
params:{id_user:$rootScope.session.id_user}
}).success(function(response){
return response;
}).error(function(err){
return false;
});
};
或者更简单:
this.getAll = function(){
return $http({
method:'GET',
url:'http://facebook.com',
params:{id_user:$rootScope.session.id_user}
});
};
此外,您可能应该阅读 How do I return the response from an asynchronous call?
关于javascript - Angular js - 从方法外部返回和 console.log $http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409106/