0

在 $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 url 是正确的,你有什么问题吗?

4

2 回答 2

1

这将解决您发送正文的问题。

  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;
    });
 });
于 2014-02-17T09:30:38.033 回答
1

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

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)。您可以在请求完成后为要执行的承诺提供回调。

您可能会对我在您的示例中提到.then(successCallback, errorCallback)和使用的内容感到困惑。提供.success(callback)的泛型promise具有方法,但服务在返回承诺后提供快捷方式,但最终是同一件事。$q.then$http.success().error()

于 2014-02-17T07:08:41.267 回答