我来自嵌入式C背景,并且在AngularJs 1.x中自学;我怀疑我的问题是一个通用的JS问题,而不是特定于AngularJs。
我在代码中发现了这种重复模式:
$http.get(url)
.success(function(data, status, headers, config)
{
console.log('Success');
});
})
.error(function(data, status, headers, config)
{
console.error('Error !');
});
作为C的人,我对lambadas并不相似,尽管我对回调很满意。
成功和失败部分的代码可能非常大,这使代码看起来很混乱-特别是将所有代码作为参数传递。
我猜测$http
的参数是(一个或多个)承诺。
是否可以通过某种方式使代码更加模块化,并使其更易于阅读和维护?
例如,我想我可以声明一些成功/失败函数并调用它们,例如:
function it_succded(data, status, headers, config))
{
console.log('Success');
});
function it_failed(data, status, headers, config)
{
console.error('Error !');
});
$http.get(url)
.success(function(data, status, headers, config)
{
it_succded(data, status, headers, config))
});
})
.error(function(data, status, headers, config)
{
it_failed(data, status, headers, config)
});
});
当然,我可以对其进行编码并查看,但是在这里提出问题是因为我想学习,并希望得到真正了解此事的人的解释,最好是那些专业(Angular)Js的人进行解释。
答案 0 :(得分:1)
要使用Promise接口,请勿使用.success()
或.error()
:它们是deprecated。而是使用.then()
和catch()
。这些回调收到的参数略有不同:
$http.get(url).then(function(response) {
console.log("Success", response.data);
}).catch(function(response) {
console.log("Error", response.status);
});
response
是一个具有预期properties的对象:
data
– {string|Object}
–使用转换函数转换的响应主体。status
– {number}
–响应的HTTP状态代码。headers
– {function([headerName])}
–标头获取函数。config
– {Object}
–用于生成请求的配置对象。statusText
– {string}
–响应的HTTP状态文本。xhrStatus
– {string}
– XMLHttpRequest的状态(完成,错误,超时或中止)。您确实可以单独定义回调函数,然后您的回调参数可以只是函数引用:
function it_succded(response) {
console.log("Success", response.data);
}
function it_failed(response) {
console.log("HTTP Error", response.status, response.statusText);
}
$http.get(url).then(it_succded).catch(it_failed);
您可以将这些函数定义为方法,例如在$scope
对象上:
$scope.it_succded = function (response) {
console.log("Success", response.data);
$scope.data = response.data;
}
$scope.it_failed = function (response) {
console.log("HTTP Error", response.status, response.statusText);
}
$http.get(url).then($scope.it_succded).catch($scope.it_failed);
小笔记:请注意,当Promise实现调用这些回调时,将不会设置this
。因此,要么不要在其中使用this
,要么将它们定义为箭头函数(然后this
就等于词汇上下文中的东西),然后将这些函数绑定到特定的this
对象,或提供少量包装回调:
.then(function(response) {
return $scope.it_succded(response);
})
答案 1 :(得分:-1)
是的,可以。
$http({
your configs
})
.then(funtion(result){ // function on success
return result.data // this is important as AngularJS $http will bind the data from the server into this variable
},
function(errorResponse){
if(errorResponse.status === 401){
// your code for handling 401 errors
}
else if(errorResponse.status === 404){
// your code for handling 404 errors
}
else if(errorResponse.status === 500){
// your code for handling 500 errors
}
})
.then(function(data){
// another function to process data
return data
})
.then(function(data){
// yet another function to process data
return data
})
我们可以根据需要组合任意多个回调。 您可以从以下链接中了解有关承诺的更多信息:https://scotch.io/tutorials/javascript-promises-for-dummies
希望它会对您有所帮助。