🏠 🌐
Connecting Angular to Spring Boot: Bridging the Frontend and
Backend
When building a full-stack application, connecting the Angular frontend to the
Spring Boot backend is crucial for seamless data flow. Let’s dive into how to
configure Angular services to consume REST APIs from a Spring Boot backend
while addressing common challenges like CORS and headers.
1. Setting Up the Spring Boot Backend
Ensure your Spring Boot application exposes REST APIs:
Create a Spring Boot Controller:
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}
}
Handle CORS (Cross-Origin Resource Sharing): Add the @CrossOrigin
annotation to allow requests from your Angular application:
@CrossOrigin(origins = "http://localhost:4200")
Or, define a global CORS configuration:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}
2. Configuring Angular Services
Angular services act as the bridge between the frontend and backend, enabling
HTTP communication.
Import HttpClientModule: Add HttpClientModule in your Angular module to
enable HTTP requests:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [...],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create a Service for API Calls: Use Angular’s HttpClient to call Spring Boot REST
APIs:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class EmployeeService {
private baseUrl = 'http://localhost:8080/api/employees';
constructor(private http: HttpClient) { }
getEmployees(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
createEmployee(employee: any): Observable<any> {
return this.http.post(`${this.baseUrl}`, employee);
}
}
3. Handling API Requests in Angular Components
Inject the EmployeeService into your component:
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees: any[] = [];
constructor(private employeeService: EmployeeService) { }
ngOnInit(): void {
this.getEmployees();
}
getEmployees(): void {
this.employeeService.getEmployees().subscribe(
data => this.employees = data,
error => console.error('Error fetching employees', error)
);
}
}
Use Angular’s two-way binding and event handling to display and interact with
data in the template.
4. Testing the Connection
. Start the Spring Boot server (http://localhost:8080).
. Run the Angular development server (http://localhost:4200).
. Verify API requests using:
○ Browser DevTools: Check the Network tab for HTTP requests and
responses.
○ Postman: Test endpoints directly to ensure correct responses.