Im trying to make a Interceptor in AngularJS. I'm quite new to AngularJS and found some examples of Interceptor, but can't get it to work.
Here I have my app.js file, which have all relevant code. I also have a controller which calls a REST api and get JSONP returned.
First I declare the module and then config it (define the Interceptor). It should now catch all requests and output to console...
Is it wrong to create the Interceptor with 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);
});
};
});
$httpProvider.responseInterceptors
are deprecated. You can modify your codeSee Docs for more info