Integrating Angular Application with Restful API
From this topic we will update our angular todoList Application with Restful API's.
Let's start with our welcome page and add a button, on clicking of that button we will call our webservice. Angular provide us HTTP client module which we are going to use using observable.
Before starting make sure you java and angular application is started.
After adding button you have to add getWelcomeMessage() method in your welcome.commponent.ts file and print something for now in console.
Now we will connect the java service for that let's create a service in angular which will connect to backend java service, for creating a service we will command ng generate service service/data/welcomeData.
you have to use this service in your welcome component by using dependency injection and update your getWelcomeMessage() method as below.
Now we will see the use of HTTP Client Module that angular provides and in this module we have something HTTP Client, we can use HTTP client to call HTTP requests like get, post, put etc.
One thing we have to do is to add Http client module to our app.module.ts file under import Section other wise you will face error as shown below
one more thing you can observe in Network tab of inspect element that no request is going to our java application or no service is getting invoked.
So what is happening here the service is not getting invoked but we are seeing observable in our console.
observables is one of the best approaches to implementing a synchronous communication. What angular does is, it makes extensive use of observables as the interface for most of the asynchronous operations. So if you want to make an object's request using the HTTP module, angular internally makes use of this observable.
so update your welcome.component.ts getWelcomeMessage() code take out the calling of service and subscribe it.
Now Click on button you will see in network tab that java service is getting invoked but having CORS failure.
This is because by default springboot prevents calling service from another web service. so we have add another annotation to our rest controller i.e. @CrossOrigin as shown below
Now refresh your page and click on button you can see java service getting invoked. So as soon as we subscribe the observable or java service gets invoked.
Now we show the message in UI Page when we click on button, let's add one method in welcome.component.ts i.e. handleSuccessulResponse(response) so when success response come it will call handleSuccessulResponse.
What we want to do, is we would want to get the welcome message from the response. for that let's create a class as shown below in welcome-data.service.ts
Now update welcome.component.ts as below
Now we show it on UI for that update code as below:
In Next Topic we will on configuring Error Response.
Comments
Post a Comment