Home > database >  Is it possible to use one interceptor in Angular to modify HTTP requests and responses?
Is it possible to use one interceptor in Angular to modify HTTP requests and responses?

Time:11-16

I learned Angular through an online course in which the instructor appeared to have used a single interceptor to modify the header on outgoing requests, and to capture the response data (or, that's what I think is happening.) Below is a screenshot taken during the course - Please ignore the comments, those were made for my personal reference.

enter image description here

Is something like this possible? Or, are separate interceptors required to modify an outgoing request and manipulate an incoming response?

I've researched online but couldn't find an instance where an interceptor was used for both purposes.

CodePudding user response:

You can combine the handling of outgoing and incoming requests in a single interceptor (exactly as shown in the image). Incoming responses can be handled in the pipe that was defined on next.handle(modifiedRequest).

There are multiple rxjs operators available that can be passed to the pipe (depending on your needs). For actually manipulating an incoming response, you can simply pass the map operator (https://www.learnrxjs.io/learn-rxjs/operators/transformation/map) to the pipe. In your case tap (https://www.learnrxjs.io/learn-rxjs/operators/utility/do) was used in order to perform side effects (like logging the response).

The question is whether you should use a single interceptor to perform both tasks. If the request and response manipulation are related to each other, then my answer is probably yes. If they are handling entirely different use-cases, I suggest you to split them up into separate interceptors in order to structure your code better.

  • Related