[英]Handling Errors In Angular Promises
我仍在學習有角度的promise,並在兩次發出“ GET”請求的地方有這段代碼。 我想在調用另一個之前運行一個get請求。 一切正常,但是如何處理錯誤? 如果在第一個GET請求中遇到錯誤,如何找出錯誤並阻止代碼調用第二個GET請求? 我的代碼示例將最有幫助。
apiServices.login = function(user,password,callback) {
$http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/login/login/?username="+user+"&password="+password+"")
.then(function(contentResponse){
resultsObject.content = contentResponse;
return $http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/data/list/");
})
.then(function(dataResponse){
resultsObject.reports = dataResponse;
resultsObject.success = 1;
console.log(resultsObject);
callback(resultsObject);
apiServices.useData(resultsObject);
});
}
dummyData.login(username, password, function (dataStatus) {
if (dataStatus.success = 1) {
$rootScope.loggedIn = true;
$rootScope.selectedDashboard = 1;
} else {
console.log("Error");
}
});
我會做一些與Lucas稍有不同的事情,我更喜歡鏈接一個catch塊(基本上它的行為就像我們使用的同步try...catch
塊一樣),而不是添加一個錯誤回調函數,因此代碼如下:
return $http.get(url1)
.then(function(result){
resultsObject.url1 = result;
return $http.get(url2);
}).then(function(result){
resultsObject.url2 = result;
return resultsObject;
}).catch(function(error){
// handle error.
});
PS:您的大多數代碼都可以,但是我不確定為什么要使用該callback(resultsObject);
,當您使用諾言時,回調是多余的,您可以只返回諾言鏈$http.get...
您可以在第一個回調處理中傳遞第二個參數。 如果請求中有錯誤,這將觸發,然后您可以根據需要進行處理:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
或在您的編碼中:
$http.get('/someUrl').then(successCallback, errorCallback);
更多信息在這里
您的代碼如下所示:
$http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/login/login/?username="+user+"&password="+password+"")
.then(function(contentResponse){
resultsObject.content = contentResponse;
return $http.get("http://magainteractive.com/prototypes/cisco-ima-dashboard/cms/web/api/data/list/");
}, function(error){
//HANDLE ERROR HERE
})
.then(function(dataResponse){
resultsObject.reports = dataResponse;
resultsObject.success = 1;
console.log(resultsObject);
callback(resultsObject);
apiServices.useData(resultsObject);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.