How to Integrate Angular 11 with Spring Boot Rest API

In this tutorial, I will show you step by step to integrate Angular 11 project with Spring Boot Rest API so that Spring Boot and Angular 11 will run in one project. You will also know how to configure Angular 11 SPA Routing to avoid Whitelabel Error Page.

Related Posts:
Angular 11 + Spring Boot + MySQL example
Angular 11 + Spring Boot + PostgreSQL example
Angular 11 + Spring Boot + MongoDB example
Angular 11 + Spring Boot: Pagination example
Angular 11 + Spring Boot: JWT Authentication example
Angular 11 + Spring Boot: File upload example

Newer version: How to Integrate Angular 12 with Spring Boot Rest API


Angular 11 & Spring Boot application Overview

Assume that we have 2 projects: Angular 11 & Spring Boot:

integrate-angular-11-with-spring-boot-project-structure

For example, if we run them separately:

  • Spring Boot Server exports Rest Apis at Url: http://localhost:8080/
  • Angular 11 Client runs at url: http://localhost:8081/

Using Angular 11 to call Spring Rest API:

integrate-angular-11-with-spring-boot-example-separate-port

Otherwise, when deploying Angular 11 production-build with Spring Boot project, we only need to run Spring Boot Project for the fullstack (Angular 11 + Spring Boot) system.

In this example, we access http://localhost:8080/.

integrate-angular-11-with-spring-boot-example

Technology Stack

  • Node.js
  • Angular 11
  • Spring Boot 2
  • Spring Tool Suite
  • Maven 3.6.1

Setup Angular 11 Client

You can use your own Angular 11 Project, or just download the source code on Github, or follow these steps to create a new one.

Open cmd and use Angular CLI to create a new Angular 11 Project as following command:

ng new AngularClient
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS

We also need to generate some Components and Services:

ng g s services/tutorial

ng g c components/add-tutorial
ng g c components/tutorial-details
ng g c components/tutorials-list

Now you can see that our project directory structure looks like this-

integrate-angular-11-with-spring-boot-project-structure-angular

Because I want to keep this tutorial simple and brief, please continue to develop this App with instruction in the post:
Angular 11 CRUD Application example with Web API

Import Angular 11 Project to Spring Tool Suite

Open Spring Tool Suite, right click on Package Explorer and choose Import -> General -> Projects from Folder or Archieve, press Next.

Find the Angular Project that we’ve just created above and press Finish, angular-client is imported like this:

integrate-angular-11-with-spring-boot-project-angular-sts

To clean the source code in STS, we need to remove node_modules folder by following the steps:

  • Right click on angular-client project, choose Properties, then Resource -> Resource Filter.
  • Press Add Filter…, choose Filter Type: Exclude all, Applies to: Files and folders, and check All children (recursive), with ‘File and Folder Atributes’, we specify node_modules:
  • integrate-angular-11-with-spring-boot-project-angular-sts-node-modules

Press OK, then Apply, the result will be like this:

integrate-angular-11-with-spring-boot-project-angular-sts-refresh

Setup Spring Boot Server

You can use your own Spring Boot Project, or just download the source code on Github, or follow these steps to create a new one.

Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.

Then open pom.xml and add these dependencies:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

The instruction can be found in the post:
Spring Boot, Spring Data JPA – Rest CRUD API example

Now we have 2 projects together in Spring Tool Suite:

integrate-angular-11-with-spring-boot-project-structure

Let’s continue to the most important part.

Integrate Angular 11 with Spring Boot Rest API

Build Angular 11 App

Currently Angular Client and Spring Boot server work independently on ports 8081 and 8080.

The first thing we need to do is to build Angular App for production.
There are 2 steps:
– Set the output directory to static folder:
Open angular.json, add the "outputPath": "./static" option to the build target so that the production will be stored in static folder under project root directory.

{
  ...
  "projects": {
    "Angular11ClientCrud": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "./static",
            "index": "src/index.html",
            "main": "src/main.ts",
            ...
          },
          "configurations": {
            ...
          }
        },
        ...
      }
    }},
  "defaultProject": "Angular11ClientCrud"
}

– Run command ng build --prod.

Generating ES5 bundles for differential loading...
ES5 bundle generation complete.

chunk {2} polyfills-es2015.5b10b8fd823b6392f1fd.js (polyfills) 36.2 kB [initial] [rendered]
chunk {3} polyfills-es5.8e50a9832860f7cf804a.js (polyfills-es5) 126 kB [initial] [rendered]
chunk {0} runtime-es2015.c5fa8325f89fc516600b.js (runtime) 1.45 kB [entry] [rendered]
chunk {0} runtime-es5.c5fa8325f89fc516600b.js (runtime) 1.45 kB [entry] [rendered]
chunk {1} main-es2015.1fc85a54f08d1dacb8cd.js (main) 280 kB [initial] [rendered]
chunk {1} main-es5.1fc85a54f08d1dacb8cd.js (main) 345 kB [initial] [rendered]
chunk {4} styles.3ff695c00d717f2d2a11.css (styles) 0 bytes [initial] [rendered]
Date: 2021-05-30T15:34:14.655Z - Hash: 86d212a6faf72b219de3 - Time: 90679ms

Now you can see new static folder with content as following:

integrate-angular-11-with-spring-boot-build-angular-production

Integrate Angular production into Spring Boot Project

Now we need to copy all files from Angular static folder to src/target/classes/static folder of Spring Boot project.

There are 2 way to do this:

  1. Manually copy/paste
  2. Using maven-resources-plugin

Open pom.xml, add following plugin:

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>

    <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <executions>
        <execution>
          <id>copy-resources</id>
          <phase>validate</phase>
          <goals>
            <goal>copy-resources</goal>
          </goals>
          <configuration>
            <outputDirectory>${basedir}/target/classes/static/</outputDirectory>
            <resources>
              <resource>
                <directory>${basedir}/../angular-client/static</directory>
              </resource>
            </resources>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

In the code above, we specify outputDirectory for the destination folder, and resource>directory for the source folder.

Run and Check Result

Build and run the Spring Boot server with commands:
mvn clean install
mvn spring-boot:run

Open browser with url: http://localhost:8080/.
The result:

integrate-angular-11-with-spring-boot-example

Spring Boot + Angular: Whitelabel Error Page

Oh yeah! Everything looks good.
But wait, let’s try to refresh the page.
What happened?

integrate-angular-11-with-spring-boot-angular-whitelabel

To handle this error, we’re gonna enable hash(#) in App Routing module.

– Open app-routing.module.ts
– Pass optional parameter useHash as true value.

@NgModule({
  imports: [RouterModule.forRoot(routes, {useHash: true})],
  exports: [RouterModule]
})

Our Url is hashed(#) after port number: http://localhost:8080/#/tutorials

integrate-angular-11-with-spring-boot-spa-example

Now you can refresh the page without worrying about Whitelabel Error.

Conclusion

Today we’ve learned how to integrate Spring Boot Project with Angular 11 Application in one Project. We also handle “Whitelabel Error Page” case for Spring Boot + Angular 11 Project.

There are many Spring Boot + Angular 11 examples that you can apply this approach to integrate:
Angular 11 + Spring Boot + MySQL example
Angular 11 + Spring Boot + PostgreSQL example
Angular 11 + Spring Boot + MongoDB example
Angular 11 + Spring Boot: Pagination example
Angular 11 + Spring Boot: JWT Authentication example
Angular 11 + Spring Boot: File upload example

Further Reading

Newer version: How to Integrate Angular 12 with Spring Boot Rest API

Leave a Reply

Your email address will not be published. Required fields are marked *