Getting started

First of all we need to create the base structure of our interceptor and provide it in our main AppModule:

Please note that you can define multiple interceptors and therefore the order matters! Interceptors are executed from the top to the bottom for outgoing requests and bottom to top for incoming server responses.

This simple code will let any request pass through untouched. Since this is not what we want, we will add some simple logic to check whether or not we are in localhost (we probably do not want this interceptor in production) and if we have a configuration for the current url.

As you can see, the code is fairly simple: all the magic is happening inside the buildHTTPResponse method. Here we retrieve the configuration for the URL and check if it needs to be an HttpResponse (status 200) or an HttpErrorResponse (status > 400):

That’s it! All that is left to do is to configure it, using the mimicConfiguration property we defined. You can both store your configuration inline (for small JSON responses) or just define it in a separate file and import it.

Wrapping up

Before coming up with this code I was trying to achieve the same results using the included webpack dev-server proxy configuration + json-server but the fact that I have to use localhost as my API endpoint forces me to have the full backend up and running.

This solution, instead, allows me to point my app towards the test or production backend and handle only the requests I’m interested in while letting the others flow.

Let me know if you have any suggestions, improvements or alternative ways of achieving the same goal.

Thanks for reading, here’s the full code: