How to Connect an Angular Frontend with a Spring Boot Backend

How to Connect an Angular Frontend with a Spring Boot Backend

Introduction

Integrating an Angular frontend with a Spring Boot backend is a common approach for building full-stack web applications. Angular, a powerful frontend framework, communicates with the backend via HTTP requests, while Spring Boot provides a robust REST API to handle business logic and data persistence.

In this guide, we will cover:

  • Setting up the Spring Boot backend
  • Creating the Angular frontend
  • Connecting Angular with Spring Boot using HTTP requests


Step 1: Set Up the Spring Boot Backend

1.1 Create a Spring Boot Application

You can generate a Spring Boot project using Spring Initializr:

  • Dependencies: Spring Web, Spring Boot DevTools, Spring Data JPA, H2 Database (or MySQL/PostgreSQL if needed).
  • Packaging: Jar

Once the project is generated, extract and open it in an IDE (e.g., IntelliJ IDEA or VS Code).

1.2 Create a Simple REST API

Modify src/main/java/com/example/demo/controller/UserController.java:

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "https://localhost:4200") // Allow Angular to access this API
public class UserController {
    
    @GetMapping
    public ResponseEntity<String> getUsers() {
        return ResponseEntity.ok("Hello from Spring Boot!");
    }
}
        

1.3 Run the Spring Boot Application

Use the command:

mvn spring-boot:run
        

Your backend should be running on https://localhost:8080.


Step 2: Create the Angular Frontend

2.1 Generate an Angular Project

Run the following command:

ng new angular-app
cd angular-app
        

2.2 Install Angular HTTP Client

Run:

npm install @angular/common
        

Then, open src/main.ts and ensure you provide the HTTP client globally:

import { provideHttpClient } from '@angular/common/http';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()],
}).catch(err => console.error(err));
        

Step 3: Connect Angular to Spring Boot

3.1 Create an Angular Service to Call the API

Run:

ng generate service services/user
        

Modify src/app/services/user.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = 'https://localhost:8080/api/users';

  constructor(private http: HttpClient) {}

  getUsers(): Observable<string> {
    return this.http.get(this.apiUrl, { responseType: 'text' });
  }
}
        

3.2 Use the Service in a Component

Modify src/app/app.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
  selector: 'app-root',
  template: '<h1>{{ message }}</h1>',
})
export class AppComponent implements OnInit {
  message: string = '';

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.userService.getUsers().subscribe(data => this.message = data);
  }
}
        

Step 4: Run and Test the Integration

4.1 Start the Angular Application

Run:

ng serve
        

Your Angular app should be running on https://localhost:4200.

4.2 Verify the Connection

  • Open the browser and go to https://localhost:4200.
  • You should see "Hello from Spring Boot!" displayed on the page.


Conclusion

By following these steps, you have successfully connected an Angular frontend with a Spring Boot backend. You can now extend this setup by adding authentication, CRUD operations, and database interactions.

要查看或添加评论,请登录

Kalana Heshan的更多文章

社区洞察

其他会员也浏览了