Angularjs从http.get获取值

时间:2017-05-19 09:03:29

标签: angularjs http promise

我需要从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

2 个答案:

答案 0 :(得分:1)

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

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

可以在$http.get( ...)之前执行。您应该加入.then来电的$http声明:

$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);
});

答案 1 :(得分:0)

您的代码无效,因为在$http.then函数内,$scope并未引用您尝试从该函数外部访问的$scope response.data。为了使其工作,您需要将.then(function (response) {$scope.$parent.my = response.data;...} 放在$ parent范围内,如下所示:

.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;
}

然后你可以像这样调用控制器中的函数:

event_detail.html