【问题标题】:Angular js - return and console.log $http response from outside the methodAngular js - 从方法外部返回和 console.log $http 响应
【发布时间】:2014-04-19 23:40:48
【问题描述】:

您好,我的代码非常简单,但我无法将 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

那么如何实现呢?

【问题讨论】:

标签: javascript angularjs http response promise


【解决方案1】:

在你的界面中 - 你应该让getAll 是一个承诺。您需要使用.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?

【讨论】:

  • 嘿本吉!!它有效,谢谢!谢谢,我希望你没有忘记我:D 玩得很开心;)
  • @sbaaaang 我没有,坦率地说,我认为您应该阅读“如何从 AJAX 调用返回响应”帖子:) 祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多