0

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 ????

1
  • 1
    There is multiple way to do it, you can use long pooling, web socket or a library. I personaly prefer web socket but it might be challenging. And you must ensure your target browsers support web socket protocol. developer.mozilla.org/en-US/docs/Web/API/WebSockets_API Commented Jan 14, 2022 at 21:28

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This would only describe the communication path from the frontend to the backend. The approach I am looking for is from backend to frontend. As @ierhalim already commented this would be possible for example via web socket or long pooling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.