January 7, 2025

17 sec read

How to Use Angular CLI with Spring Boot: A Detailed ...

Integrating Angular CLI with Spring Boot allows you to build powerful, full-stack applications efficiently. Angular hand...

Post Details

Integrating Angular CLI with Spring Boot allows you to build powerful, full-stack applications efficiently. Angular handles the front end, while Spring Boot takes care of the back end. This guide will walk you through the steps to set up and connect these two technologies seamlessly.

Why Combine Angular CLI with Spring Boot? Using Angular and Spring Boot together provides a robust solution for web development:

*** Angular CLI** offers powerful tools for building dynamic, single-page applications. *** Spring Boot** simplifies the development of back-end APIs with Java.

  • Together, they enable seamless integration between the front-end UI and back-end business logic.

Prerequisites Before starting, ensure you have the following installed on your system:

  1. Java Development Kit (JDK) (Version 11 or later)
  2. Node.js (Includes npm)
  3. Angular CLI (Run npm install -g @angular/cli)
  4. Spring Boot Initializer (Accessible via Spring Initializr)
  5. An IDE (e.g., IntelliJ IDEA for Spring Boot and VS Code for Angular)

Step 1: Set Up the Spring Boot Back End 1.1 Create a New Spring Boot Project

  1. Visit Spring Initializr.
  2. Configure your project:
  • Project: Maven
  • Language: Java
  • Spring Boot Version: Latest stable version Dependencies: Add the following:
    • Spring Web
    • Spring Boot DevTools
    • Spring Data JPA (for database interactions)
    • H2 Database (for testing purposes)
  • Group, Artifact, and Name: Customize them as needed.
  1. Click Generate, download the project, and extract it.

1.2 Add a Sample REST API In the extracted project, navigate to src/main/java/[packagename] and create a new controller:

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class DemoController {

    @GetMapping("/greeting")
    public String getGreeting() {
        return "Hello from Spring Boot!";
    }
}

1.3 Run the Spring Boot Application

  1. Open the project in your IDE.
  2. Run the DemoApplication class.
  3. Verify the API works by visiting http://localhost:8080/api/greeting in your browser or using Postman.

Step 2: Set Up the Angular Front End 2.1 Create a New Angular Project

  1. Open a terminal and run:
  ng new angular-spring-app

  1. Choose Angular routing and your preferred CSS preprocessor (CSS, SCSS, etc.).

2.2 Serve the Angular Application Navigate to the project directory and run:

  cd angular-spring-app
  ng serve

Visit http://localhost:4200 to verify that the Angular app is running.

Step 3: Connect Angular with Spring Boot 3.1 Install HTTP Client in Angular Angular provides HttpClient for making HTTP requests. Install it if it's not already included:

  ng add @angular/common/http

3.2 Create a Service for API Communication In your Angular project, generate a service:

ng generate service services/api

Modify the generated service file (src/app/services/api.service.ts):

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

@Injectable({
  providedIn: 'root',
})
export class ApiService {
  private apiUrl = 'http://localhost:8080/api/greeting';

  constructor(private http: HttpClient) {}

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

3.3 Modify a Component to Display Data Update the AppComponent to use the ApiService:

  1. Modify the app.component.ts file:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'Angular-Spring App';
  greeting = '';

  constructor(private apiService: ApiService) {}

  ngOnInit(): void {
    this.apiService.getGreeting().subscribe((data) => {
      this.greeting = data;
    });
  }
}

  1. Update the app.component.html file to display the greeting:
<div>
  <h1>{{ title }}</h1>
  <p>{{ greeting }}</p>
</div>

Step 4: Enable Cross-Origin Requests (CORS) in Spring Boot To allow Angular to communicate with Spring Boot, enable CORS in the back end:

1. Add the following configuration class to your Spring Boot project:

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200");
            }
        };
    }
}

2. Restart the Spring Boot application.

Step 5: Test the Integration

  1. Start the Spring Boot application (http://localhost:8080).
  2. Start the Angular application (http://localhost:4200).
  3. Visit http://localhost:4200 in your browser. You should see the greeting message from the Spring Boot API displayed on the Angular front end.

Step 6: Build and Serve the Angular App with Spring Boot 6.1 Build the Angular Project 1. Run the following command in the Angular project directory:

ng build --prod

2. The build files will be generated in the dist/angular-spring-app folder.

6.2 Serve Angular Files with Spring Boot

  1. Copy the build files into the src/main/resources/static folder of your Spring Boot project.

  2. Modify the Spring Boot controller to serve the Angular app:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

  1. Restart the Spring Boot application. Now, your Angular front end will be served directly by Spring Boot.

Conclusion By following this guide, you’ve successfully set up Angular CLI with Spring Boot and created a working full-stack application. This setup enables you to develop powerful web applications that leverage Angular’s dynamic UI capabilities and Spring Boot’s robust back-end framework.

Happy coding! 🚀


Related Posts

Views: Loading...

DevJourney is a platform for developers to showcase their projects, skills, and journey. Join us to track your progress!

developed by Sixtusdev | version 0.1.0