gpt4 book ai didi

javascript - Anjgularjs 中的 $http : Can someone explain the flow

转载 作者:行者123 更新时间:2023-12-02 17:45:14 25 4
gpt4 key购买 nike

在 $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 正确,您发现任何问题吗?

最佳答案

据我了解,a参数是一个回调函数,在收到服务器回复时执行。这破坏了 $q 服务提供的 promise 的目的。另外,$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 请求,并返回一个具有方法 .then(successCallback, errorCallback) 的 Promise 对象。您可以为请求完成后执行的 promise 提供回调。

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

关于javascript - Anjgularjs 中的 $http : Can someone explain the flow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com