[英]AngularJS $http and how to get error response
我看到以下示例用於調用服務器端資源:
UserSession.prototype.$save = function() {
return $http.post('/users/sign_in', {
"user" : {
"email" : this.email,
"password" : this.password,
"remember_me" : this.remember_me ? 1 : 0
}
});
};
我的問題是,如果調用失敗,是否可以在此代碼中看到實際的錯誤響應? 上面如何寫呢?
您錯過了回調
UserSession.prototype.$save = function() {
return $http.post('/users/sign_in', {
"user" : {
"email" : this.email,
"password" : this.password,
"remember_me" : this.remember_me ? 1 : 0
}
})
.success(function (data, status, headers, config) {
// success logic here
})
.error(function (data, status, headers, config) {
// error logic here
});
};
您需要使用.error()
回調參考
UserSession.prototype.$save = function() {
return $http.post('/users/sign_in', {
"user" : {
"email" : this.email,
"password" : this.password,
"remember_me" : this.remember_me ? 1 : 0
}
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
您可以像其他答案所建議的那樣在該函數中定義.success
和.error
回調,但是我覺得您更有可能希望調用.$save
的應用程序代碼確定成功或失敗時要完成的工作。
因此,您將按原樣保留.$save
函數,並且在應用程序中的任何地方調用myUserSession.$save()
,您都可以執行以下操作:
myUserSession.$save()
.success(function(data, httpStatus, header, config) {
...
})
.error(function(data, httpStatus, header, config) {
...
});
這樣做只會使代碼更具可重用性。 當然,如果您知道關於保存的事實,那么您到處都希望有完全相同的行為,那么就按照其他答案所建議的去做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.