我試圖在AngularJS中製作一個攔截器。我對AngularJS頗爲陌生,發現了一些攔截器的例子,但無法使其工作。攔截器不工作
這裏我有我的app.js文件,它有所有相關的代碼。我也有一個控制器,它調用REST API並返回JSONP。
首先我聲明模塊,然後配置它(定義攔截器)。它現在應該捕獲所有請求並輸出到控制檯...
使用app.factory創建攔截器是錯誤的嗎?
var app = angular.module(
'TVPremieresApp',
[
'app.services'
, 'app.controllers'
]
);
app.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor');
});
app.service('MessageService', function() {
// angular strap alert directive supports multiple alerts.
// Usually this is a distraction to user.
//Let us limit the messages to one
this.messages = [];
this.setError = function(msg) {
this.setMessage(msg, 'error', 'Error:');
};
this.setSuccess = function(msg) {
this.setMessage(msg, 'success', 'Success:');
};
this.setInfo = function (msg) {
this.setMessage(msg, 'info', 'Info:');
};
this.setMessage = function(content, type, title) {
var message = {
type: type,
title: title,
content: content
};
this.messages[0] = message;
};
this.clear = function() {
this.messages = [];
};
});
app.factory('errorInterceptor', function ($q, $location, MessageService, $rootScope) {
return function (promise) {
// clear previously set message
MessageService.clear();
return promise.then(function (response) {
console.log(response);
return response;
},
function (response) {
if (response.status == 404) {
MessageService.setError('Page not found');
}
else if(response.status >= 500){
var msg = "Unknown Error.";
if (response.data.message != undefined) {
msg = response.data.message + " ";
}
MessageService.setError(msg);
}
// and more
return $q.reject(response);
});
};
});
您正在使用的angularjs的版本見Docs? – Satpal
responseInterceptors已被棄用。檢查http://stackoverflow.com/a/20632690/1014586看看你如何適應你的代碼 – mbarthelemy