Angular 9 Spring Boot Example (2024)
Overview
Angular is extremely famous for modern web application development and Spring Boot and Angular are a strong and developer-friendly combination if you want to create the full stack web application.
The new Angular 9 version is available now. The newest release again includes improvements in performance, the default is the Ivy renderer, smaller bundle size and many more. Check out Angular 9 features.
In this article, we begin exploring how to build a full-stack application and how to expose an endpoint by Spring Boot and use Angular 9 to consume it and show the data.
- first we will create an Angular application with mock data
- create spring boot rest application, which will provide api
- Finally we will integrate api with Angular application
Lets start
Angular Project Setup:
First prerequisites we need to develop Angular application is Node js.
Node.js :
Node.js is a JavaScript runtime, Node.js is commonly used to simplify the development of Angular applications
Angular applications can be built and hosted using the Angular CLI Node.js module
Once built, the Angular application can be deployed without requiring Node.js, can be deployed into any web server
Installtion :
npm -g install npm
Angular applications can be built and hosted using the Angular CLI Node.js module
Once built, the Angular application can be deployed without requiring Node.js, can be deployed into any web server
Angular CLI :
Angular CLI provides a set of utilities to simplify Angular development. Angular CLI is run using the ng command
- Create a new project ng new
- Create a new Component ng generate component. You can also use ng generate directive/pipe/service/class/module
- Build and execute ng serve
- Run tests ng test
- Create a production build ng build --prod
npm install @angular/cli@9.0.2 -g
Your system has been configured now, We can check the angular cli version with command ng version
Checkout our related posts :
Creating and Running an Angular Application
As our setup is ready, creating a new Angular application is easy with the Angular CLI,
- simply type below command
ng new airline-client-web
This creates a new project, Within a new folder named "airline-client-web"
- Go inside the newly created project, Type cd "airline-client-web"
- to start To get the angular project, We must go inside the "airline-client-web" folder and then use the following command.
ng serve
- Wait for the "Compiled successfully" message
- Open Chrome and go to http://localhost:4200, You should see the airline-client-web app is running!
Angular CLI creates a standard directory structure and initial Component in app directory for our project, lets look at our project structure
Click here to understand more about Angular.
Flight Model
Since our Angular application will fetch from and persist Flight entities in the database, let's implement a simple domain model flight with TypeScript.
Let's open a terminal console and create a model directory and then and within that directory, issue the following command:
ng generate class flight
Here is code for our my flight Model
export interface Flight{
flightNumber : string;
origin : string;
destination : string;
}
Flight service
ng generate service flight
Here is code for flight service
import { Injectable } from '@angular/core';
import { Flight } from "../model/flight";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from "rxjs";
@Injectable()
export class FlightsService {
private MYFLIGHTS: Flight[] = [
{"id": 11, "flightNumber" : "FS1298", "origin": "LAX", "destination" : "LHR", "departDay" : "Thursday",
departTime : "09:00", "arriveDay" : "Monday", arriveTime : "09:00", "price" : 99.99},
{"id": 12, "flightNumber" : "FS1201", "origin": "LAX", "destination" : "LHR", "departDay" : "Friday",
departTime : "09:00", "arriveDay" : "Monday", arriveTime : "09:00", "price" : 99.99},
];
constructor(private http: HttpClient) { }
// to test with local mock data
public getMyFlights() : Flight[]{
return this.MYFLIGHTS;
}
}
Create My Flights Component
We will be creating My Flights Component which will fetch data from spring boot service and display it later.
Lets begin with the My Flights component Open a command prompt and use the following command-
ng generate component my-flights
Here is code for our my flight template component
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th>Flight</th>
<th>From</th>
<th>To</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let flight of flights">
<td>{{flight.flightNumber}}</td>
<td>{{flight.origin}}</td>
<td>{{flight.destination}}</td>
</tr>
</tbody>
</table>
here is our component source
import { Component, OnInit } from '@angular/core';
import {Flight} from '../model/flight';
import {FlightsService} from "../services/flights.service";
@Component({
selector: 'app-my-flights',
templateUrl: './my-flights.component.html',
styleUrls: ['./my-flights.component.css']
})
export class MyFlightsComponent implements OnInit {
private flights : Flight[];
constructor(private flightService: FlightsService) {}
ngOnInit() {
this.flights = this.flightService.getMyFlights();
}
}
Next in the app-routing.module.ts we will be defining the url for accessing this component-
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MyFlightsComponent } from './my-flights/my-flights.component';
const routes: Routes = [
{ path:'', component: MyFlightsComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In app.component.html we will only keep the single line as below
<router-outlet></router-outlet>
Finally we need to update app.module.ts to declare MyFlightsComponent, import HttpClientModule and update providers for FlightsService as below
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MyFlightsComponent } from './my-flights/my-flights.component';
import { FlightsService } from 'src/app/service/flights.service';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
MyFlightsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [FlightsService],
bootstrap: [AppComponent]
})
export class AppModule { }
Now If we goto localhost:4200 and we can see the following output with mock data
Now let move to creting our service api with Spring boot
Creating a simple Spring Boot Application:
We will be creating a simple Spring Boot Application to expose a REST endpoint to return a mocking the list of entities.
- Go to Spring on official site (https://start.spring.io/).
- Select Maven project, add dependencies
- Click on Generate the project Button.
- Save and extract the project.
- Open IDE and import the project and click on browse and select the extracted project folder where pom.xml resides.
- Once project gets imported, follow below steps to create controller.
- Project Structure
- It will generate Main Class as given below with SpringBootApplication annotation.
package com.techgeeknext.airline;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
package com.techgeeknext.airline.model;
public class Flight {
private String flightNumber;
private String origin;
private String destination;
public Flight(String flightNumber, String origin, String destination) {
this.flightNumber = flightNumber;
this.origin = origin;
this.destination = destination;
}
public String getDestination() {
return this.destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getFlightNumber() {
return this.flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public String getOrigin() {
return this.origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
package com.techgeeknext.airline.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.techgeeknext.airline.model.Flight;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class HomeController {
/**
* Selects the home page and populates the model with a message
*/
@RequestMapping(value = "/flights", method = RequestMethod.GET)
public List <Flight> getFlights(Model model) {
// Requesting flights
List <Flight> flightList = new ArrayList<Flight>();
flightList.add(new Flight("FS2211", "NYC", "GRM" ));
flightList.add(new Flight("FS2211", "LHR", "ARN" ));
return flightList;
}
}
mvn spring-boot:run
or start the application by running main() method from the main class (EmpTaskApplication.java). It will start the embedded tomcat server on port 8080.
Service API Integration with Angular :
Now our both Angular and Spring Boot projects are ready, lets integrate them together
We will consume the service api from our angular service using the Angular HTTPClient for calling the Spring Boot API to fetch the data.
So let Also create a new method in our flights.service.ts which makes call to the spring boot application using the defined httpClient.
import { Injectable } from '@angular/core';
import { Flight } from "../model/flight";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from "rxjs";
@Injectable()
export class FlightsService {
private MYFLIGHTS: Flight[] = [
{"flightNumber" : "FS1298", "origin": "LAX", "destination" : "LHR"},
{"flightNumber" : "FS1201", "origin": "LAX", "destination" : "LHR"},
];
constructor(private http: HttpClient) { }
// to test with local mock data
public getFlightsMockData() : Flight[]{
return this.MYFLIGHTS;
}
// to test with service api
public getFlightsData() : Observable<Flight[]>{
let url = "http://localhost:8080/flights";
return this.http.get<Flight[]>(url);
}
}
Note : We have we need to added the HTTPClientModule in imports of the app.module.ts intially
Consume Service from component
As we already injected FlightService in our MyFlightsComponent, we simply has to add one more method to invoke the http call by subscribing to it.
Click here to know more about Obserables and Subscriber.
import { Component, OnInit } from '@angular/core';
import {Flight} from '../model/flight';
import { FlightsService } from 'src/app/service/flights.service';
@Component({
selector: 'app-my-flights',
templateUrl: './my-flights.component.html',
styleUrls: ['./my-flights.component.scss']
})
export class MyFlightsComponent implements OnInit {
private flights : Flight[];
constructor(private flightService: FlightsService) {}
ngOnInit() {
//this.flights = this.flightService.getFlightsMockData();
this.getFlightsData();
}
// get the data from backend service api
private getFlightsData() {
this.flightService.getFlightsData().subscribe(data => {
this.flights = data;
});
}
}
Here we have commented out our mock data assignment and instead calling getFlightsData() method to make call to api
Running the Application End to End :
Finally, we're ready to run our application as both spring boot and Angular application is running
Now if you go to localhost:4200, you can see our integration output in browser
Next we will see Angular + Spring Boot JWT Authentication Example
Download Source Code
The full source code for this article can be found on below.Download it here - Angular Spring Boot Example