Smart Tech for a better Web
This is similar to create an Angular.js service. First, we need to create our application module and depend our bootstrapping to the $provide and $httpProvider services.
With that we can create our interceptor, which is basically created like a Angular.js service.
$provide is a service which adds the “myHttpInterceptor” factory to the Dependency Injection Manager. The $http service will need to look it up later. Of course this is no black magic, we need to add our interceptor to the list of response interceptors with the following line, right after we created the interceptor service:
After that, we can already start with the implementation of the interception method itself
Here we created two callbacks, one for success and the second one for failure. Both handlers call the safeJson method with response.data, which is holding the actual data from the server. The second one does a reject of further interception. In my specific case, the data block does hold the reasons for rejection.
As I will not outline the concept of promises in this blog post, you might want to take a look at the great promise docs from Angular.js.
Fur convenience, here is the full code, including the safeJson method which reduces /**/ from my server string.
As a last word, I have had a custom way how I deal with the JSON problem. If you don’t have a custom problem and can freely choose, you might want to look at the build in mechanics which solves exactly my problem, just without additional code.