Angular 6 – Send Nested Object to Spring Boot Server example

In this tutorial, we’re gonna create an Angular 6 Client App that sends nested object (complex object) to a Spring Boot Server.

Related Posts:
AngularJs POST-GET Nested Objects to SpringBoot server
Jquery Ajax POST-GET Nested Objects to SpringBoot server

Technologies

– Angular 6
– RxJS 6
– Java 1.8
– Spring Boot 2.0.4.RELEASE
– Maven 3.3.9
– Spring Tool Suite – Version 3.9.0.RELEASE

Example Overview

1. Angular 6 App Client

angular-6-send-nested-object-spring-boot-server-example-ui

The nested object will be like this:

{
   "name": "Andrien",
   "age": 27,
   "address": {
      "street": "Alexander",
      "postcode": "123456"
   }
}

This client sends HTTP POST to server.

2. Spring Boot Server

The goal of this server is to provide a REST API that can receive HTTP POST and show data.

angular-6-send-nested-object-spring-boot-server-controller-overview

Practice

1. Angular 6 App Client

angular-6-send-nested-object-spring-boot-server-example-angular-client-structure

Run command for generating Angular Component and Service:
ng g s customer
ng g c customer-form

1.1 App Module

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { CustomerFormComponent } from './customer-form/customer-form.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomerFormComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
1.2 Customer Service

customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

import { Customer } from './customer.inteface';

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

  private static readonly POST_CUSTOMER_URL = '/api/post/customer';
  private headers = new HttpHeaders({ 'Content-Type': 'application/json' });

  constructor(private http: HttpClient) { }

  createCustomer(customer: Customer): Observable {
    return this.http.post(CustomerService.POST_CUSTOMER_URL, customer, { headers: this.headers });
  }
}

With customer interface:

export interface Customer {
  name: string;
  age: number;
  address: Address;
}

export interface Address {
  street: string;
  postcode: string;
}
1.3 Component for submitting Customer

customer-form.component.ts

import { Component, OnInit } from '@angular/core';
import { Customer } from '../customer.inteface';
import { CustomerService } from '../customer.service';

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

  customer: Customer = { name: '', age: 0, address: { street: '', postcode: '' } };

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
  }

  onSubmit() {
    this.customerService.createCustomer(this.customer).subscribe(
      value => {
        console.log('[POST] create Customer successfully', value);
      }, error => {
        console.log('FAIL to create Customer!');
      },
      () => {
        console.log('POST Customer - now completed.');
      });
  }

}

customer-form.component.html

Customer Data



1.4 App Component

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'grokonez';
  description = 'Angular-SpringBoot Demo';
}

app.component.html

{{title}}

{{description}}

1.5 Integrate Spring Boot Server with Angular 6 client

– Create proxy.conf.json file under project:

{
	"/": {
		"target": "http://localhost:8080",
		"secure": false
	}
}

– Edit package.json file for “start” script:

...
"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
},
...
2. Spring Boot Server

angular-6-send-nested-object-spring-boot-server-example-spring-server-structure

2.1 Create Spring Boot project

With Dependency:


	org.springframework.boot
	spring-boot-starter-web

2.2 Create Data Model

model/Address.java

package com.grokonez.spring.getobject.model;

public class Address {
	private String street;
	private String postcode;

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getPostcode() {
		return postcode;
	}

	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}

	@Override
	public String toString() {
		return "Address [street=" + street + ", postcode=" + postcode + "]";
	}
}

model/Customer.java

package com.grokonez.spring.getobject.model;

public class Customer {
	private String name;
	private Integer age;
	private Address address;

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Customer [name=" + name + ", age=" + age + ", address=" + address + "]";
	}

}
2.3 Create Controller

controller/CustomerController.java

package com.grokonez.spring.getobject.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.grokonez.spring.getobject.model.Customer;

@Controller
public class CustomerController {

	private final static String POST_CUSTOMER_URL = "/api/post/customer";

	@PostMapping(POST_CUSTOMER_URL)
	public ResponseEntity createCustomer(@RequestBody Customer customer) {

		System.out.println("Creat Customer: " + customer);

		return ResponseEntity.ok(customer);
	}
}
Check Results

Run Spring Boot Server and Angular 6 Client App (npm start), go to http://localhost:4200/:

angular-6-send-nested-object-spring-boot-server-example-ui

Click Submit button to send Customer Data, check Server Console:

Creat Customer: Customer [name=Andrien, age=27, address=Address [street=Alexander, postcode=123456]]

Check Browser Console:

angular-6-send-nested-object-spring-boot-server-example-angular-client-result

Sourcecode

Angular6SendObject
SpringBootRestObject



By grokonez | August 9, 2018.


Related Posts


Got Something To Say:

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

*