Asqan Asqan - 6 months ago 26
AngularJS Question

Interceptors are not triggered

I'm trying to implement a global authorization handling for my app.

Here you see my code:

.factory('Request', ['$resource', 'general',
function ($resource) {
return $resource(baseURL + ':resourceName/', {}, {
get : {
method : 'GET',
isArray : true,
transformResponse : function (data, headers) {
return JSON.parse(data).data;
},
interceptor: {
request : function (data) {
console.log("test");
},
requestError : function (data) {
console.log("test");
},
response : function (data) {
console.log("test");
},
responseError : function (data) {
console.log("test");
if(data.state == 401){
general.logIn({},false,function(){});
}
}

}
}
});
}
]);


However, none of the interceptors is triggered. What is wrong with code?

Answer

According to the Angular documentation, an interceptor when used in $resource only has two valid methods for the interceptor object:

interceptor - {Object=} - The interceptor object has two optional methods - response and responseError. Both response and responseError interceptors get called with http response object. See $http interceptors.

See: https://docs.angularjs.org/api/ngResource/service/$resource

If you require the request methods as well, you would have to follow the documentation here: https://docs.angularjs.org/api/ng/service/$http

Also, I noted that you have defined responseError twice, instead of response and responseError:

responseError : function (data) {
    console.log("test");
},
responseError : function (data) {
    console.log("test");
    if(data.state == 401){
        general.logIn({},false,function(){});
    }
}