Spring Boot + Angular 12 Full Stack Simple Example(2021) | CodeUsingJava


































Spring Boot + Angular 12 Full Stack Simple Example(2021)

Angular and Spring Boot forms a great combination to form a powerful combination for developing a fullstack production grade applications. Inside Angular, the complete code is broken down into components and helps in providing an organised functionality.
TypeScript is one of the primary languages in Angular. One of the great advantages offered by typescript is that the code is debugged directly in the editor, So errors can be caught while developing the application. The flow of Spring Boot with Angular can be explained by the following digram-
Flow Digram

Installation of Angular-

First, we install nodejs from the official site.
Now inside command prompt, type npm install -g @angular/cli
We check the version of angular by ng version
Angular cli

This shows that Angular is successfully installed in your system.
Let us move to our project now:-

Spring Boot Project Structure

This will be the standard directory layout for maven project structure-
Spring Boot Maven Project
We need to start by creating a Maven pom.xml(Project Object Model) file. The pom.xml file contains the project configuration details.
	<?xml version="1.0" encoding="UTF-8"?>
	<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
		<modelVersion>4.0.0</modelVersion>
	
		<groupId>com.codeusingjava</groupId>
		<artifactId>CustomersSpringBoot</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<packaging>jar</packaging>
	
		<name>CustomersSpringBoot</name>
		<description>Demo project for Spring Boot</description>
	
		<parent>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-parent</artifactId>
			<version>2.1.0.RELEASE</version>
			<relativePath /> <!-- lookup parent from repository -->
		</parent>
	
		<properties>
			<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
			<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
			<java.version>1.8</java.version>
		</properties>
	
		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-web</artifactId>
			</dependency>
		</dependencies>
	
		<build>
			<plugins>
				<plugin>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-maven-plugin</artifactId>
				</plugin>
			</plugins>
		</build>
	
	
	</project>
	
Creating the model class for the Customers-
	package com.codeusingjava.model;

public class Customers {

	private String firstName;
	private String lastName;

	protected Customers() {
	}

	public Customers(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[ firstName='%s', lastName='%s']", firstName, lastName);
	}
}

Now we create the controller class for the application-
This class contains the RestPoints that are needed to be exposed.
The @CrossOrigin annotation specifies that the endpoints can be called from other domains also. In our case, the origin is specified as localhost: 4200.
	package com.codeusingjava.controller;

	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.codeusingjava.model.Customers;
	
	@RestController
	@CrossOrigin(origins = "http://localhost:4200")
	public class HelloController {
		
		@RequestMapping(value = "/Customers", method = RequestMethod.GET)
		public List <Customers> getCustomers(Model model) {
			List <Customers> customerList = new ArrayList<Customers>();
			customerList.add(new Customers("abc", "xyz" ));
			customerList.add(new Customers("a2", "b2" ));
			
			return customerList;
		}
	
	}
	
The main class for the Spring boot application is as follows-
package com.codeusingjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CustomerApplication {

	public static void main(String[] args) {
		SpringApplication.run(CustomerApplication.class, args);
	}
}


When we run the Spring Boot application, we get the output as follows-
Spring Boot output

Angular Project Structure

Firstly, we create a new project of Angular by the following command-
ng new Customers-Angular
create angular project
The project Structure for the Angular application is as follows-
Angular Project Structure
When we run the command ng-serve, the program will be started.
Now go to http://localhost:4200 , we see the following screen:
angular console
Now we need to create a Customers Component which will be used for integrating with spring boot application and get the data.
angular component
Inside the app-routing.module.ts, the url for accessing the component is defined-
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CustomersComponent } from './customers/customers.component';

const routes: Routes = [
  { path:'', component: CustomersComponent},
];

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

We keep the app-component.html class as follows-
The router outlet is responsible for loading the dynamic componments based on current route state.
	<router-outlet></router-outlet>
Now if we refresh the url http://localhost:4200, we get our output as follows-
angular component
Now we create a service named as HttpClientService.
By this service, the get request from the Spring Boot application is to be called.
angular service
Now we write the code to httpclient.service.ts file. The HttpClient will be used for calling the API to get the data of customers.
When we mark a class with @Injectable annotation, the class can be used with the dependency injector.
 
	import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class Customers{
  constructor(
    public firstName:string,
    public lastName:string,
  ) {}
}

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

  constructor(
    private httpClient:HttpClient
  ) { 
     }

     getCustomers()
  {
    console.log("test call");
    return this.httpClient.get<Customers[]>('http://localhost:8080/Customers');
  }
}

Inside the app.module.ts, we add the HttpClientModule to app.module.ts
 
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersComponent } from './customers/customers.component';

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

Inside the CustomersComponent, we need to register the service which is used for integration and fetching data with Spring Boot.
We use constructor dependency injection for the folllowing process.
 
	import { Component, OnInit } from '@angular/core';
	import { Customers, HttpClientService } from '../service/http-client.service';
	
	@Component({
	  selector: 'app-customers',
	  templateUrl: './customers.component.html',
	  styleUrls: ['./customers.component.css']
	})
	export class CustomersComponent implements OnInit {
	   customers:Customers[] = [];
	
	  constructor(
		private httpClientService:HttpClientService
	  ) { }
	
	  ngOnInit() {
		this.httpClientService.getCustomers().subscribe(
		 response =>{this.customers=response;},
		);
	  } 
	}	
To display the data to the user, in a tabular form, we write the customers.component.html file as follows-
 
<table border="1">
    <thead></thead>
    <tr>
      <th>firstName</th>
      <th>lastName</th>
      </tr>
    
    <tbody>
        <tr *ngFor="let cust of customers">
            <td>{{cust.firstName}}</td>
            <td>{{cust.lastName}}</td>
            </tr>
    </tbody>
      </table>
When we run the program, we get the output as follows-
angular final output

Downloads-

Angular Code
Spring Boot Code