Connecting Angular to Spring Boot
Connecting Angular to Spring Boot
@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);
}
}
@CrossOrigin(origins = "http://localhost:4200")
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}
@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:
@Injectable({
providedIn: 'root',
})
export class EmployeeService {
getEmployees(): Observable<any> {
return this.http.get(`${this.baseUrl}`);
}
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
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.
responses.
○ Postman: Test endpoints directly to ensure correct responses.