Angular how to return value from http.post success

2019-07-21 09:31发布

i have a code in my angular controller

$scope.message = '';
$http.post('/save/').success(function(data) {                  
    $scope.message = "success";
});
console.log($scope.message);
//get empty string?

why after i run, i get empty string on $scope.message? how http.post when success return value because i want to reuse the value for my another function. thanks anyway.

3条回答
smile是对你的礼貌
2楼-- · 2019-07-21 10:01

why after i run, i get empty string on $scope.message?

The success callback for $http is called asynchronously, when the response is available. This explains why the console.log() can run before the callback. If another function needs the value, @ShaiRez provided two solutions already:

  1. call the other function inside the success callback
  2. $watch the value, and call the other function inside the $watch listener callback
查看更多
在下西门庆
3楼-- · 2019-07-21 10:04

What about doing -

$scope.message = '';
$http.post('/save/').success(function(data) {                  
    $scope.message = "success";
    console.log($scope.message);
});

?

or am I missing something else?

查看更多
迷人小祖宗
4楼-- · 2019-07-21 10:14

What you are looking for is this:

$scope.$watch("message", function(value){
  console.log($scope.message);
}); 

Here is a sample plnkr example I've made

查看更多
登录 后发表回答