【问题标题】:AngularJS - Return in success $http.postAngularJS - 成功返回 $http.post
【发布时间】:2015-02-12 20:21:19
【问题描述】:

我使用 AngularJs,我需要在 $http.post 连接后返回一个数据。这是代码:

app.controller('PrincipalController',['$http', '$scope', function($http,$scope){
  $scope.myData = 0;
  $http.post("server/checklogin.php",
    {id: "id",email: "email",password: "password"}
  )
  .success(function(data){
    console.log($scope.myData) //0
    $scope.myData = data;
    console.log($scope.myData); // 1
}

OLD:如何将数据传递到 myData? - 感谢您的回答,如果我解释得不好,请见谅。

但是现在,在 html 中,{{myData}} 我能写什么?

我不知道它是否是基本的,但我必须将“myData”与“ng-if”一起使用..

编辑:谢谢!我想我已经解决了! :D

【问题讨论】:

  • 对不起,我无法理解这个问题,你只是在'success'函数中执行'myData = data',有什么问题?
  • 无论您想对数据做什么,都必须成功。由于异步性质,你不能把它带到外面。
  • 做你想做的事情的唯一有角度的方法,即以同步方式使用异步检索的数据是使用 $resource 服务,它将填充你的 myData 变量(假设它在 $scope 中)当数据从服务器返回时。 $http 不会立即提供此功能,唯一可以使用返回数据的地方是回调。
  • 要么使用this.myData or $scope.myData,要么同时使用
  • @entre ok.. 但它不起作用.. 我该怎么办?

标签: angularjs angular-http


【解决方案1】:

通常在您的服务中,您会回报承诺

myService.getCheckLogin = function {
    return $http.post("server/checklogin.php",
      {id: "id",email: "email",password: "password"}
      );
}

然后在控制器中

myService.getCheckLogin()
.success(function(data){
  $scope.myData = data;
}
.error(function(err){
  console.log(err);
}

【讨论】:

  • 不应该在.error调用之前关闭成功方法的')'?
【解决方案2】:

你应该这样做:

.success(function(data){
    $scope.myData = data;
    //OR
    myCallback(data);
    console.log(data) //data = 1 (server works);
}

你不能在 post 调用之后立即进行赋值,因为调用是异步的,你无法预测它返回的确切时间。

我使用了$scope,因为通常您可以通过控制器上的服务来使用它,其中范围可用。否则你可以在回调中使用函数

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多