Refactoring Angular and Java Application code
In This topic we will refactor our code for better readability.
Refactor JAVA Code :
Let's start with JAVA Code so you can see in previous few topic we have added cross origin annotation in each controller to call API from Angular application. what will happen if you have lots of Controller then there will a chance we miss adding it.
So what we will do ? For now we will add a bean in RestWebserviceApplication.class which will handle cross origin. We are going to use WebMvcConfigurer and will override addCorsMappings as per our project needs.
WebMvcConfigurer : It is an Interface which is used to customized JAVA Configuration for spring MVC enabled project.
addCorsMappings/CorsRegistry : It is a default method provided by WebMvcConfigurer to configure global cross origin request.
Update your code as shown below and once you add this you can remove CrossOrigin annotation from Controller class.
Check from UI if your application is working fine after this change.
Refactor Angular Code :
After adding these code you have to add APP_INITIALIZER in app.module.ts which is used as Dependency Injection token.
Now if you go http://localhost:4200/loginand refresh it in Inspect > Network tab you can see environment.json file gets loaded. As I earlier said that the function that we create is executed during the application bootstrap process, and the needed data is available on startup.
Comments
Post a Comment