[英]$http/$q/promise Questions (in Angular)
當$ q / $ http應該觸發onReject
塊時,我似乎無法onReject
。
假設我有一個基本電話:
$http.get('/users')
.then(function(res) {
return res.data;
}, function(err) {
console.log(err);
});
如果出現500 Internal Server Error
我將結束於onSuccess
塊。 從我對承諾的微不足道的理解中,我猜這似乎是正確的,因為我從技術上確實得到了回應? 問題是onSuccess
塊似乎是錯誤的地方,有一堆
if(res.status >= 400) {
return $q.reject('something went wrong: ' + res.status);
}
只是為了讓我的onReject
塊能夠運行。 這是應該工作的方式嗎? 大多數人是在onSuccess
塊中處理400多個狀態,還是返回被拒絕的承諾來強制onReject
塊? 我是否缺少更好的方法來解決此問題?
我嘗試在httpInterceptor
執行此操作,但找不到從此處返回被拒絕的諾言的方法。
this.responseError = function(res) {
if(res.status >= 400) {
// do something
}
return res;
};
您的成功障礙將不會受到打擊。 嘗試此操作,如果錯誤代碼> 300,則會看到錯誤塊。
$http.get('/users').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
您可以在攔截器中處理這些,而不是在回調中處理。
在您的app.config中,您可以將$ httpProvider配置為如下所示:
$httpProvider.interceptors.push(['$q', function ($q) {
return {
request: function (config) {
//do something
return config;
},
responseError: function (response) {
if (response.status === 401) {
//handle 401
}
return $q.reject(response);
}
};
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.