【问题标题】:Angularjs Get value from http.get [duplicate]Angularjs从http.get获取价值[重复]
【发布时间】:2017-10-19 07:56:54
【问题描述】:

我需要从 http.get 函数中获取价值,但我不知道如何。 请帮忙。

这是我的代码

$http.get(base_url+"user/feach_one")
   .then(function (response) {$scope.my = response.data;

     $scope.email=$scope.my.email;
     console.log("email from get:"+$scope.email);

});

console.log("Get email from outside:"+$scope.email);

这是控制台中的结果:

Get email from outside:undefined
myangular.js:90 email from get:myemail@yahoo.com

【问题讨论】:

  • 您做对了,您将能够从“.then”之外获取值,但只有在解决后。你想做什么 ?在解析请求之前调用外部的 console.log,但值是在您的范围对象中设置的
  • 确保 url 正确 - 调试它 - 查看浏览器控制台错误类型

标签: angularjs http promise


【解决方案1】:

$http 是一个异步调用,所以这一行:

console.log("Get email from outside:"+$scope.email);

可以在$http.get( ...)之前执行。您应该在$http 调用的.then 语句中输入:

$http.get(base_url+"user/feach_one").then(function (response) {
    $scope.my = response.data;
    $scope.email=$scope.my.email;
    console.log("email from get:"+$scope.email);
    console.log("Get email from outside:"+$scope.email);
});

【讨论】:

  • 我的问题是如何获得它。从外面
  • @Vuong 一旦承诺得到解决,您就可以按预期将它与$scope.email 一起使用。
【解决方案2】:

您的代码不起作用,因为在 $http.then 函数内部,$scope 没有引用您尝试从函数外部访问的同一 $scope。为了使其工作,您需要将 response.data 放在 $parent 范围内,如下所示:

.then(function (response) {$scope.$parent.my = response.data;...}

或者,您可以从 .then 函数中返回一个值,并将其分配给控制器中的 $scope(假设您正在为 $http 请求使用服务)。

function makeHttpReq(okcallback, errorCallback) {

    $http.get(base_url+"user/feach_one")
      .then(function (response) {
        okCallback(response.data)
    });

然后您可以像这样在控制器中调用该函数:

makeHttpReq(function (data) {
    $scope.my = data;
}

【讨论】:

    猜你喜欢
    • 2012-09-19
    • 2019-05-11
    • 2017-11-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多