How to pass data from Spring backend to Angular frontend?
I know my question is a bit general, but I couldn't find anything on this. How do you pass data from the Spring backend to the Angular front end? What would be the best approach?
A quick example:
I want to develop a microservice to be integrated from other system. I want to provide a REST interface with which the user can trigger events in the frontend. Now when a user makes a REST request, how do I pass the message to the Angular frontend?
Frontend -> Backend REST
Backend -> Frontend ????
First you can define an endpoint with Spring Boot:
@GetMapping(value = "/test", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<String> test() {
return ResponseEntity.ok("Hello world");
}
For development you would need to turn off CORS:
@Profile("dev")
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET")
.allowedOrigins("http://localhost:4200");
}
}
and then you can easily subscribe on data in Angular method:
onClick(): void {
this.subscribed = this.http.get('http://localhost:8080/test', {responseType: 'text'})
.subscribe(data => this.message = data);
}