AngularJS - Return in success $http.post

纵然是瞬间 提交于 2019-12-12 14:09:03

问题


I use AngularJs and I need to return a data after a $http.post connection. This is the code:

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: How can I pass the data into myData? - Thanks for your answers and sorry if I haven't explained well.

But now, in html, {{myData}} what can I write?

I do not know if it's fundamental, but I'll have to use "myData" with an "ng-if"..

EDIT: Thanks! I think that I've solved! :D


回答1:


Typically in your service you will return the promise

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

then in controller

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



回答2:


you should do something like this:

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

You cannot put the assignment right after the post call, because the call is asynchronous, you cannot predict the exact moment when it will be returning.

I used the $scope, because normally you might use it through a service on a controller where a scope is available. Otherwise you can use a function in a callback



来源:https://stackoverflow.com/questions/28476111/angularjs-return-in-success-http-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!