Angular 7 + Spring Boot Application: Hello World Example

  • 2019-03-08 02:04 AM
  • 947

In this tutorial, we will create a full-stack application where we expose an endpoint using Spring Boot and consume this endpoint using Angular 7 and display the data.

In this tutorial, we will create a full-stack application where we expose an endpoint using Spring Boot and consume this endpoint using Angular 7 and display the data. In the next tutorial, we will be further enhancing this application and performing CRUD operations.

Angular 7 + Spring Boot CRUD Demo

Angular 7 + Spring Boot Application Hello World Example

Angular 7 + Spring Boot Application CRUD Example

Angular 7 + Spring Boot Application Login Example

What Is a Full-Stack Application?

In a full-stack application, we expose the backend point to get the data. This data can then be used by any application or device as per the developer’s need. In the future, even if another front-end device is to be used, there will not be much change and the new device will need to consume these endpoints.

This tutorial is explained in the below Youtube Video -

Spring Boot Application

We will be creating a simple Spring Boot Application to expose a REST endpoint to return a list of employees. In a previous tutorial, we had seen how to fetch the data using Spring Boot JDBC. However, for this tutorial, we will be mocking the list of employees to be returned. Maven Project will be as follows:Spring Boot ApplicationThe Maven will be as follows:

<?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.javainuse</groupId>
<artifactId>SpringBootHelloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringBootHelloWorld</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.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>

Create the SpringBootHelloWorldApplication.java file as shown below:

package com.javainuse;

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

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

Create the Employee model class as follows

package com.javainuse.model;

public class Employee {
private String empId;
private String name;
private String designation;
private double salary;

public Employee() {
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public String getDesignation() {
	return designation;
}

public void setDesignation(String designation) {
	this.designation = designation;
}

public double getSalary() {
	return salary;
}

public void setSalary(double salary) {
	this.salary = salary;
}

public String getEmpId() {
	return empId;
}

public void setEmpId(String empId) {
	this.empId = empId;
}

@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((designation == null) ? 0 : designation.hashCode());
	result = prime * result + ((empId == null) ? 0 : empId.hashCode());
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	long temp;
	temp = Double.doubleToLongBits(salary);
	result = prime * result + (int) (temp ^ (temp >>> 32));
	return result;
}

@Override
public boolean equals(Object obj) {
	if (this == obj)
	return true;
	if (obj == null)
	return false;
	if (getClass() != obj.getClass())
	return false;
	Employee other = (Employee) obj;
	if (designation == null) {
		if (other.designation != null)
		return false;
	} else if (!designation.equals(other.designation))
	return false;
	if (empId == null) {
		if (other.empId != null)
	return false;
	} else if (!empId.equals(other.empId))
	return false;
	if (name == null) {
		if (other.name != null)
		return false;
	} else if (!name.equals(other.name))
	return false;
	if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
	return false;
	return true;
	}
}

@RequestMapping maps the /employee request to return a list of employees. Also, here we are using the Cross-Origin annotation to specify that calls will be made to this controller from different domains. In our case, we have specified that a call can be made from localhost:4200.

package com.javainuse.controllers;

import java.util.ArrayList;
import java.util.List;

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.javainuse.model.Employee;

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

	private List<Employee> employees = createList();

		@RequestMapping(value = "/employees", method = RequestMethod.GET, produces = "application/json")
		public List<Employee> firstPage() {
			return employees;
	}

		private static List<Employee> createList() {
			List<Employee> tempEmployees = new ArrayList<>();
			Employee emp1 = new Employee();
			emp1.setName("emp1");
			emp1.setDesignation("manager");
			emp1.setEmpId("1");
			emp1.setSalary(3000);

			Employee emp2 = new Employee();
			emp2.setName("emp2");
			emp2.setDesignation("developer");
			emp2.setEmpId("2");
			emp2.setSalary(3000);
			tempEmployees.add(emp1);
			tempEmployees.add(emp2);
			return tempEmployees;
	}
}

Compile and run SpringBootHelloWorldApplication.java as a Java application. Go to localhost:8080/employees.Spring Boot Application Output

Angular 7 Development

Installing Angular CLI

  • Install Node.js by downloading the installable from Install Node.js.* Install Angular CLI using the following command. It wll get us the latest version of Angular CKI.

    npm install -g @angular/cli
    

    angular cli 7 install*
    We can check the Angular LI version, like so:

    ng version
    

    angular cli 7 version*
    Next, we will create a new Angular project using the Angular CLI as follows:

    ng new employee-management
    

    angular cli 7 new project*
    To get the Angular CLI project started use the following command. We must go inside the employee-management folder and then use it.

ng serve

angular cli 7 start

Go to localhost:4200 angular 7 hello worldI will be using the Microsoft Visual Studio Code IDE for Angular. Let’s import the project we developed earlier in Microsoft Visual Studio Code IDE. Our final Angular project’s file structure will be as follows: 
angular 7 application

TypeScript

TypeScript is a superset of JavaScript. It is a strongly typed language. So, unlike with JavaScript, we know if some syntax is wrong while typing it and rather than having to wait until runtime. In Angular, it is compiled to JavaScript while rendering the application in the browser.

Component

angular components and servicesIn Angular, we break complex code into reusable parts called components. A major part of development with Angular 7 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser.

Service

In Angular, we might have scenarios where some code needs to be reused in multiple components. For example, a data connection that fetches data from a database might be needed in multiple components. This is achieved using services.

Create the Employee Component

We will be creating an employee component which will fetch data from Spring boot and display it. Lets begin with the employee component. Open your terminal and use the following command:

ng generate component employee

angular generate component
For this, Angular will have created the following four files:

  • employee.component.ts
  • employee.component.spec.ts
  • employee.component.html
  • employee.component.css

Next, in the app-routing.module.ts file, we will be defining the URL for accessing this component.

If we got o localhost:4200, we can see the following output 
employee component works

Create HttpClient Service

Next, we will be creating an HTTPClient Service. This service will have the httpClient and will be responsible for calling HTTP GET requests to the backend Spring Boot application. In Angular, a service is written for any cross-cutting concerns and may be used by more than one components

ng generate service service/httpClient

angular generate service
The following service files are created:

  • http-client.service.ts
  • http-client.service.spec.ts

We will be modifying the http-client.service.ts file. In the constructor define the HTTPClient instance we will be using to make a call to the Spring Boot application. Here we will be using the Angular HTTPClient for calling the Spring Boot API to fetch the employee data. Also, we will be creating a method which makes calls to the Spring Boot application using the defined httpClient. Also, we need to add the HTTPClientModule to the app.module.ts

Insert HttpClient Service in Employee Component

Next, using the constructor dependency injection, we will be providing EmployeeComponen as an instance of HttpClientService. Using this service we make a call to the Spring Boot application to get a list of employees.

import { Component, OnInit } from '@angular/core';
import { HttpClientService } from '../service/http-client.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  employees:string[];

  constructor(
    private httpClientService:HttpClientService
  ) { }

  ngOnInit() {
    this.httpClientService.getEmployees().subscribe(
     response =>this.handleSuccessfulResponse(response),
    );
  }

handleSuccessfulResponse(response)
{
    this.employees=response;
}

}

In the employee.component.html file, we iterate over the list of employees we got in the employee.component.ts file.

<table border="1">
  <thead></thead>
  <tr>
    <th>name</th>
    <th>designation</th>
  </tr>

  <tbody>
      <tr *ngFor="let employee of employees">
          <td>{{employee.name}}</td>
          <td>{{employee.designation}}</td>
      </tr>
  </tbody>
</table>

Go to localhost:4200

angular 7 output

And we’re done!

Originally published by Azlan Shaikh at https://dzone.com

Learn more

Angular 7 (formerly Angular 2) - The Complete Guide
The Complete Angular Course: Beginner to Advanced
NativeScript + Angular: Build Native iOS, Android & Web Apps
Build awesome web apps using Angular 7
Go Full Stack with Spring Boot and Angular 7
Angular 6 (Angular 2+) & React 16 - The Complete App Guide
NgRx In Depth (Angular 7 and NgRx 7, with FREE E-Book)
Angular & NodeJS - The MEAN Stack Guide
Learn and Understand AngularJS

Suggest