javascript - Angular js - 从方法外部返回和 console.log $http 响应

标签 javascript angularjs http response promise

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

相关文章:

javascript - "kill"在 JavaScript 中做什么?

javascript - WebRTC 和 ThreeJS 创建拉丝金属纹理立方体

angularjs - ui-router : named views (multiple) views, 保持一切分离?

vba - 来自 Excel VBA RingCentral FaxoutAPI 的 HTTP 发布

javascript - 骡子 ESB : Proceed HTTP Response with HTML and Javascript

javascript - while 条件检查中的赋值是什么?

javascript - 如何在 FOR 循环中创建暂停或延迟?

angularjs - 使用angularjs修改html表格的列数

angularjs - 检查元素属性是否存在 - Protractor

java - HTTP 错误代码,导致 IOException - 如何访问响应?