$ http服務是一個函數,它接受一個參數 - 一個配置對象 - 用於生成一個HTTP請求並返回一個承諾。
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(response); // add console log of response
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(response); // add console log of error response
});
還是一個攔截器可以用來「監視」所有的HTTP的:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (response.status === 500) {
//DO WHAT YOU WANT
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
謝謝這導致出現錯誤的正確窗口。有沒有一種方法可以防止服務器錯誤在Web瀏覽器控制檯窗口中顯示? – cAMPy
在這個例子中,我更新了responseError的'response.status === 500'。在第一個例子中,您是console.logging錯誤。或者你在說什麼控制檯錯誤? :) –
我的意思是我現在可以正確地向用戶顯示500錯誤信息。但是,如果有人啓動控制檯,則會出現:「NetworkError:500 Internal Server Error - 」和服務器的URL。這並不重要,但如果可以阻止在控制檯中顯示此消息,我希望這樣做。 – cAMPy