Angular + Spring Boot Hello World Example: Step-by-Step Tutorial

In this tutorial, we will create a simple "Hello World" application using Spring Boot for the backend and Angular for the frontend. We will handle CORS issues to ensure smooth communication between the Angular frontend and the Spring Boot backend.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • Node.js and npm installed
  • Angular CLI installed (npm install -g @angular/cli)
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed

Step 1: Setting Up the Spring Boot Backend

1.1 Create a Spring Boot Project

  1. Open Spring Initializr:

  2. Configure Project Metadata:

    • Project: Maven Project
    • Language: Java
    • Spring Boot: Select the latest version of Spring Boot 3.3
    • Group: com.example
    • Artifact: hello-world
    • Name: hello-world
    • Description: Hello World Service
    • Package Name: com.example.helloworld
    • Packaging: Jar
    • Java Version: 17 (or your preferred version)
    • Click Next.
  3. Select Dependencies:

    • On the Dependencies screen, select:
      • Spring Web
    • Click Next.
  4. Generate the Project:

    • Click Generate to download the project zip file.
    • Extract the zip file to your desired location.
  5. Open the Project in Your IDE:

    • Open your IDE and import the project as a Maven project.

1.2 Update application.properties

Open the application.properties file located in the src/main/resources directory and add the following configuration:

server.port=8080

Explanation:

  • Configures the server port to 8080.

1.3 Create HelloWorldController

Create a HelloWorldController class in the com.example.helloworld.controller package:

package com.example.helloworld.controller;

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

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class HelloWorldController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}

Explanation:

  • @CrossOrigin(origins = "http://localhost:4200"): Enables CORS for requests from the Angular frontend running on localhost:4200.
  • @RestController: Marks the class as a REST controller.
  • @RequestMapping("/api"): Maps requests to /api.
  • sayHello(): Handles GET requests to /api/hello and returns "Hello, World!".

1.4 Run the Spring Boot Application

Run the application by executing the HelloWorldApplication class. The backend should be up and running on http://localhost:8080.

Step 2: Setting Up the Angular Frontend

2.1 Create an Angular Project

  1. Open a terminal and run the following command to create a new Angular project:
ng new hello-world-client
  1. Navigate to the project directory:
cd hello-world-client

2.2 Install Dependencies

Install Bootstrap for styling:

npm install bootstrap

Add Bootstrap to angular.json:

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

2.3 Create HelloWorldService

Generate the HelloWorldService:

ng generate service services/hello-world

Edit hello-world.service.ts:

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

@Injectable({
  providedIn: 'root'
})
export class HelloWorldService {

  private baseUrl = 'http://localhost:8080/api/hello';

  constructor(private http: HttpClient) { }

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

Explanation:

  • @Injectable({ providedIn: 'root' }): Marks the service as injectable and available throughout the app.
  • HttpClient: Service for making HTTP requests.
  • getHelloWorld(): Sends a GET request to the backend and returns a string.

2.4 Create HelloWorldComponent

Generate the HelloWorldComponent:

ng generate component components/hello-world

Edit hello-world.component.ts:

import { Component, OnInit } from '@angular/core';
import { HelloWorldService } from '../../services/hello-world.service';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
  message: string = '';

  constructor(private helloWorldService: HelloWorldService) { }

  ngOnInit(): void {
    this.helloWorldService.getHelloWorld().subscribe(data => {
      this.message = data;
    });
  }
}

Edit hello-world.component.html:

<div class="container mt-5">
  <div class="row justify-content-center">
    <div class="col-md-6">
      <div class="card">
        <div class="card-header">Hello World</div>
        <div class="card-body">
          <p>{{ message }}</p>
        </div>
      </div>
    </div>
  </div>
</div>

Explanation:

  • HelloWorldComponent retrieves the "Hello, World!" message from the backend and displays it.

2.5 Update Angular Routing

Edit app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HelloWorldComponent } from './components/hello-world/hello-world.component';

const routes: Routes = [
  { path: 'hello', component: HelloWorldComponent },
  { path: '', redirectTo: '/hello', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Explanation:

  • Defines a route for the HelloWorldComponent.
  • Redirects the root path to /hello.

2.6 Update Angular App Module

Edit app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './components/hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Explanation:

  • Imports necessary modules for the Angular app.
  • Declares the components used in the app.
  • Sets up the app's root module.

2.7 Run the Angular Application

Open a terminal in the Angular project directory and run the application:

ng serve

Visit http://localhost:4200 in your web browser to see the application.

Conclusion

In this tutorial, we created a simple "Hello World" application using Spring Boot 3 for the backend and Angular 18 for the frontend. We handled CORS issues to ensure smooth communication between the Angular frontend and the Spring Boot backend. By following this structure, you can extend and customize the application as needed.

Comments