How to Intercept HTTP Requests with the HttpInterceptor - Angular 6 | 7 - CodeWithSrini

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone welcome to code with SHINee in this lecture we're going to look into HTTP interceptors so what is n HTTP interceptors interceptors is a feature in angular that provides a great way to intercept outgoing requests or incoming responses so when you make a request you can use HTTP interceptors to intercept and modify the request as you like it in other words you can mutate your outgoing requests mutation means that you can add a property in your outgoing request or you can had an add an header to your outgoing requests okay so why do you need an interceptors simple let's say you're working on a project and you may have to prefix all your API calls with a server name you can achieve that using an interceptor not just this you can think of many uses of interceptors you name a few ensure the outgoing request is HTTP or instead of HTTP and you can also set an authorization header on each request you can create a global error cache in case of HTTP request fails or you can also create a mock response for your application to test ok so let's just go ahead and create an application we just created and list reverse that into the folder so it should be HTTP intercepted demo and then open up the code base implementing an HTTP interceptor is fairly straightforward all you need to do is create a class with an injectable decorator that implements HTTP interceptor let's go ahead and create our very own interceptor now okay so for that I'm going to create a folder in the app directory called as HTTP - interceptor so basically this will hold all sorts of intercepting concepts embedded in inside this folder so we're not going to chuck every all kinds of Interceptor into a one single class we're going to separate them wait for that for now let's create a class called authentication I mean auth header for authenticating the for sending the authentication header each time when you send a request so I'm going to create a new file which is a or hello interceptor and then in here obviously we need to have an injectable so it's an injectable decorator and we're going to export that class as auth header interceptor and implements HTTP Interceptor it's not picking up let's see okay so the Interceptor doesn't except she should be command okay so we're gonna just implement that manually for now Interceptor and it should be from should be from obviously from angular and common and HTTP okay so immediately we are getting another set of squiggly lines which means every interceptor class must have I mean every class that implements intercept HTTP Interceptor must have a method called intercept right so the intercept right it takes up two arguments a request and request is of HTTP request and you can give it as any and it also takes up next okay these two are the building blocks for an interceptor so when you you can you can grab the request here and you can pass it on to the next absorb so it should be next and an HTTP handler okay and again we are getting another squiggly lines which means we need to return we need to we need to return it as an absorber which is next dot handle so it should be returned next not handle and it should be of a request okay so all the squiggly lines are gone okay this is just a basic thing and our interceptor work without any logic here okay so the logic is missing we will implement that shortly but before that let's go ahead and we we need some sort of an api service call alright so what i'm gonna do is first let me just make bit bigger so that you can see it and i'm gonna bring up the terminal so let's create a service ngg s which is ng generate service of a tester right so the service is created here so in the test service we have we need we need we need to define a HTTP here so that should be HTTP client and it's added automatically all right so we have a field in the class called HTTP using that we are going to make some HTTP calls which is not very fancy thing for now we're going to use this fetch method inside app component GS so let's do a HTTP call so HTTP doc cat and this should be this can be of any service called soldiers let's go ahead to the JSON IP code and get a mock fake JSON it could be anything anything okay I'm just going to grab this one and use it in my demo so this could be it okay so we're going to get a to rule from this fetch and the next part is we're going to go into the app component HTML which is a here before that let's let's let's run this up in G self so I'm gonna just get rid of everything here you don't need it and obviously we can have bootstrap if you want but now it's just a simple demo so we're gonna have a simple button and that button will have a click event so we should go for a fetch so what I'm showing you is a plain simple example of how to implement an HTTP interceptor in your application this is not a very complex demo once the bottle is click the fetch inside the component es will get invoked so it should be fetch and obviously we need to have a constructor and we need to define our st service so rest is just a bare minimum so s service obviously in the app component we should have this dot it's service dot fetch and that should call up obviously its we have a parameter already passing through so we need to subscribe it's an observable so obviously we need to subscribe to an HTTP response and the data and so log okay so this is pretty straightforward and we're going to listen to a fetch the button oh we forgot let's open an inspect element every time I'm getting some sort of an error okay my back in the app module we need to add an HTTP client module so that should do the trick and we have a fetch so once you do that I'm from the JSON IP code all right so this is what you see this is what we get now the thing is if you go over the network and if you look at the headers let's say we want to attach an extra param for the headers such as authorization for the security sake that's where the HTTP interceptor comes in so what shall we do now for the author let's also create something called in the XTS okay so this index tea yes will hold will be exporting some constant or a set of HTTP interceptor providers all right so they should export constant and HTTP interceptor intercept providers that will be set of array and we will do a provide and that provide will be HTTP interceptors and we need to use a class user class it's use we need to use a class call or interceptor and also there is a extra hirama called multi and that should be he said as true the multi is set as true since it will provide multiple classes for a single injection token okay the single injection token Curie's HTTP interceptors okay so for this for this injection token we are using multiple class so this is another concept from angular now why are we creating index index TS and pulling this off header inside index TS why not we can straight away use the off header inside the app module now if you ask me you can very well go ahead and do that but if you're going to build a large complex application you need to keep in mind that everything needs to be modular everything needs to be like a plug-and-play so in that case we don't want to clutter everything and chuck everything inside app module okay it should be inside a separate separate file or separate folder and then you can do all the dirty works inside this index tiers and move just the HTTP or move only this file with the app module okay only this variable all we need is this okay so let's let's see how we can make use of that yeah in the app module as a provider in this code and how it has HTTP interceptor providers and that should do the trick okay so there are no more errors let's do a control log and then it's also the auth intercept provider so we the Interceptor actually works okay you need to make a note here which is in the app module we have added HTTP interceptor provider which is them which is the most important thing only then the HTTP intercept will work okay how it works basically this one will be make use making use of the providers here and cause of the author author interceptor so the first one except the priority and and execute execute this class so this is one thing likewise if you want to do a global error caching mechanism you can just go ahead and just copy it and then create a class similar to off error and poly class error handler interceptor for the sake of naming okay so this will do the trick so you can just create your own error handling mechanism across the application when if an application typically is a so that'll be that will help you manage I mean manage the the error that's happening or if there is any slow slowness in the application or slowness in the Internet you can catch it using interceptor okay so let's go ahead and create a I mean intercept this ongoing request so let's just copy do this we will die set one by one so let's do a console.log and do a request dot URL so you will get a URL okay so this is one thing and now let's straight away go ahead and create a and header for example just imagine you have an auth authentication token like auth token or it as my auth token create a clone of your requests so basically cloning the request call off request request north cone what we're going to do is we're going to set a header or calling a property called set headers and we're going to use authorization as auth token okay so we basic mistake I'm just gonna dice it the score like this so it'll be easier to understand now instead of request we're going to send all three codes that will be the final request from this interceptor had a oh sorry for from this intercept lock class and when you do a fetch successfully go through let's take the network if you go to a request errors you will see the authorization as my auth token so this is pretty much all about intercepting your request using HTTP interceptors interceptor method except two arguments I mean request and the next request is of type HTTP request and the next is of type HTTP handler and finally the intercept method returns an observable this is an observable and in turn it will go to your application up to the the service and up to the app component es which is right over here and that's where we are subscribing the the response so this is pretty much about the HTTP interceptor please feel free to comment down in the comment section and please to subscribe to my channel and also share it if you find this tutorial very useful thank you very much bye-bye
Info
Channel: CodeWithSrini
Views: 32,772
Rating: undefined out of 5
Keywords: Angular 4, Angular 6 http Interceptor, Angular 7 http Interceptor, Angular http Interceptor, angular 6 project, angular how to, angular example, angular http, angular 6 http, angular 7 http, httpinterceptor, http headers angular, httpclient angular, httpclient, http, httpclientmodule, http interceptor angular 5”, Angular tutorial, angular course, angular lesson, web application, codewithsrini, code with srini
Id: CjAk6K7ehq4
Channel Id: undefined
Length: 13min 20sec (800 seconds)
Published: Fri Jun 28 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.