1 Followers
25 Following
infoxen

infoxen

How use proxy to handle http calls in Angular 8?

 

 

Hi guys, today we will learn about how we can use proxy to handle http calls in Angular 8.

So, firstly we will make a new Angular app with the cli command:

 

ng new angular-proxy

 

If you don’t know how to start with a Angular app then you can read my story, here is the link:

 

Setup Angular App with GitHub

 

Hi, today we will talk about how you can set up your angular app with git hub repository and track version control with…

 
 

Now, we have setup our app and this is the time to add httpClient to make http calls. We will do this in app.module.ts

 

The first view of app.module.ts will be look like this:-

 

And here is the updated view with HttpClient:

 

here you can see that we have added HttpClientModule.

 

The 2nd step is to we will make a normal http call to test and for that we will add a test button in app.component.

 

The updated code of app.component.html:

 

<div style="text-align:center"><h1>Welcome to {{ title }}!</h1><button (click)="makeHttpCall()">Test Call</button><router-outlet></router-outlet>

And in app.component.ts we will make a function to do call with a fake rest api:-

 

 

Here You can see that we have a get call with a fake api url. Now this is the time to test this . Our app is looking like this.

 

 

Now, well open network panel to check the network calls and hit a click on Test Call button.

 

Here you can see that Request URL is the which we have added in the function and we are getting status 200.


Now, this is the time to use proxy for this http call and for that we will make a new file named proxy.conf.json with parallel to node modules folder.

 

In the image you can see that target is the same url which we have used before.

 

So, according to proxy concept we will make http calls to this proxy “api” and the proxy file will hit its target url but the original url will not show in the network.

 

So, we will do some changes in the function:

 

makeHttpCall(){
this.httpClient.get('api').subscribe(res=>{
console.log(res);
})
}

You can see that we have changed the url to “api”.

This is the time run the project with proxy and for that we will run this command:

ng serve --proxy-config proxy.conf.json

 

This command will run the project with proxy.

 

Now we will test again with hit the button:

 

Here you can see that request url is changed and now it is hitting on http://localhost:4200/api but well get the same response with the original api.

So guys, that’s all for now. If you have any queries then you can ask me in the comment box.

 

Thank you…

 

 

Source: http://medium.com/@abhishek.garg_53728/use-proxy-with-angular-8-7e6e024b93b1