繁体   English   中英

Anjgularjs中的$ http:有人可以解释这个流程

[英]$http in Anjgularjs: Can someone explain the flow

在$ http调用中,我们可以在url部分传递的所有内容,我有一个服务器地址,一个用户名和密码。 我可以将所有作为json对象传递吗?或者我们还有其他任何参数(如url)。 有人可以帮助我理解成功通话中发生的事情。

具体来说,我正在努力的代码是:

app.factory('myFactory',function(){

var fact = {};
fact.getData = function(a){
    $http({method:'POST',url:'http://100.100.100.100:8080/xx/xx.xx'});
    $http.success(function(reply){a(reply)}
        );
};

return fact;

});


请参阅以下代码,我仍然没有从服务器获取数据,同时也没有错误。

xapp.factory('loginData',function($http,$log){
    var fact = {};

    fact.getData = function(cred,cb){
        return
            $http({
                method:'post',
                url:'xxx.xxx.xxx.xxx:xxxx/xxxxxx',
                data:cred})
            .success(function(data,status,header,config){
                cb(data);
                })
            .error(function(data,status,header,config){
                $log.warn(status);
                });
    };

    return fact;
});


xapp.controller('mainController',function($scope,$log,$http,loginData){
    $scope.user = {uesr:'user',password:'123'};

    loginData.getData($scope.user,function(data){
        $scope.reply = data;
        });
});

在控制台日志中,我得到一个'未定义'。 如果http网址是正确的,你看到任何问题吗?

据我了解, a参数是收到来自服务器的回复时执行的回调函数。 这会破坏$q服务提供的承诺的目的。 此外, $http服务本身没有.success回调。 它返回一个带有.success.error回调的promise对象。 这是应该怎么做的:

app.factory('myFactory', function() {
  var fact = {};
  fact.getData = function() {
    return $http.get('your/path/to/resource/');
  }
  return fact;
})
.controller('myCtrl', function($scope, myFactory) {
  myFactory.getData().then(function(response){
    //response.data holds your data from server
  }, function(){
    //this fn gets called when error happens
  });
});

一些解释: myFactory.getData()为服务器创建一个新的http请求,并返回一个promise对象,该对象有一个方法.then(successCallback, errorCallback) 您可以在请求完成后提供要执行的承诺的回调。

您可能会对我在您的示例中使用的.success(callback) .then(successCallback, errorCallback).success(callback)感到困惑。 $q提供的通用promise.then方法,但是$http服务在返回一个promise时提供了快捷方式.success().error()但最后却是一样的。

这将解决您发送身体的问题。

  app.factory('myFactory', function($http) {
    return{
       getData : function(body) {
        return $http({
          url: 'http://100.100.100.100:8080/xx/xx.xx',
          method: 'POST',
          data:body
        })
      }
   }
 });


 app.controller('myCtrl', function($scope, $location, $http, myFactory){

    var body ={username:uname, password:pass};
    myFactory.getData(body).success(function(data){
       $scope.data=data;
    });
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM