integrate-angular-with-spring-boot-feature-image

How to Integrate Angular with Spring Boot Rest API

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

Related Posts:
Angular 8 + Spring Boot: JWT Authentication example
Angular 8 + Spring Boot + MySQL/PostgreSQL example
Angular 8 + Spring Boot + MongoDB CRUD example
Angular 8 + Spring Boot: File upload example

Angular 10 + Spring Boot + MySQL example
Angular 10 + Spring Boot + PostgreSQL example
Angular 10 + Spring Boot + MongoDB example
Angular 10 + Spring Boot: JWT Authentication example
Angular 10 + Spring Boot: File upload example


Angular & Spring Boot application Overview

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

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

For example, if we run them separately:

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

Using Angular to call Spring Rest API:

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

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

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

integrate-angular-with-spring-boot-example

Technology Stack

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

Setup Angular Client

You can use your own Angular 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 Project as following command:

ng new Angular8Client
? 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-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 8 CRUD Application example with Web API

Import Angular 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-8-client is imported like this:

integrate-angular-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-8-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-with-spring-boot-project-angular-sts-node-modules

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

integrate-angular-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-with-spring-boot-project-structure

Let’s continue to the most important part.

Integrate Angular with Spring Boot Rest API

Build Angular 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": {
    "Angular8ClientCrud": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "./static",
            "index": "src/index.html",
            "main": "src/main.ts",
            ...
          },
          "configurations": {
            ...
          }
        },
        ...
      }
    }},
  "defaultProject": "Angular8ClientCrud"
}

– 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: 2020-05-30T15:34:14.655Z - Hash: 86d212a6faf72b219de3 - Time: 90679ms

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

integrate-angular-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-8-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-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-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-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 8 Application in one Project. We also handle “Whitelabel Error Page” case for Spring Boot + Angular Project.

There are many Spring Boot + Angular examples that you can apply this approach to integrate:
Angular 8 + Spring Boot: JWT Authentication with Spring Security example
Angular 8 + Spring Boot + MySQL/PostgreSQL example
Angular 8 + Spring Boot + MongoDB CRUD example
Angular 8 + Spring Boot: File upload example

Angular 10 + Spring Boot + MySQL example
Angular 10 + Spring Boot + PostgreSQL example
Angular 10 + Spring Boot + MongoDB example
Angular 10 + Spring Boot: JWT Authentication example
Angular 10 + Spring Boot: File upload example

Further Reading

2 thoughts to “How to Integrate Angular with Spring Boot Rest API”

  1. I imorted your both projects and application run

    my spring boot run on port 8083
    After that i follwed process as you said but i can not able to run frontend at port localhost :8083
    It gives error messsage
    Should i need to change port at the frontend?

  2. Sorry it work fine i was trying to access wrong url.. but now it work fine.. I found Only your tutorial is working as i expected.. Thank You Sir..

Leave a Reply

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