In the previous post, we had introduced Angular Service (Angular 4 Service) but we did it with a mock data solution. So in the tutorial, JavaSampleApproach will show you how to use Angular HTTP Client inside Angular Service to fetch data from SpringBoot RestApi.
Related articles:
– How to develop with Angular Service (Angular 4 Service)
– How to integrate Angular 4 with SpringBoot Web App and SpringToolSuite
– How to work with Angular Routing – Spring Boot + Angular 4
– How to use Angular HttpClient to POST, PUT, DELETE data on SpringBoot Rest APIs – Angular 4
– Angular 4 + Spring JPA + PostgreSQL example | Angular 4 Http Client – Spring Boot RestApi Server
– Angular 4 + Spring JPA + MySQL example | Angular 4 Http Client – Spring Boot RestApi Server
Contents
I. Technologies
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: RELEASE
– Angular 4
– Node.js
II. Angular Http Client
HTTP Client is a solution to exchange data with a remote server. Angular Http is an injectable class, which has a set of request methods:
– request(): to performs any type of http request.
– get(): performs a request with get http method.
– post(): performs a request with post http method.
– put(): performs a request with put http method.
– delete(): performs a request with delete http method.
– patch(): performs a request with patch http method.
– head(): performs a request with head http method.
– options(): to performs a request with ‘options’ http method.
In the tutorial, we will start with http get() method to fetch data from SpringBoot RestAPI.
III. Practice
Step to do:
– Create an Angular Client
– Create a SpringBoot RestApi Service
– Integrate Angular App and SpringBoot Server
– Run & Check results
1. Create an Angular Client
1.1 Create Angular project
In the tutorial, We continue to work on the project that we had done in the previous post. So please check out sourcecode to continue:
– How to develop with Angular Service (Angular 4 Service)
1.2 Provide Http service
In the previous post, we had used a mock data for simulation. But now it’s ready to delete mock-customers.ts to come with a new solution -> fetch data from SpringBoot Service by HTTP client.
For using Http module, need register it on /angular4client/src/app/app.module.ts file:
... import { HttpModule } from '@angular/http'; ... @NgModule({ ... imports: [ ... HttpModule ], ... }) export class AppModule { } |
-> HTTP client is ready to use.
1.3 Modify DataService with HttpClient
– Firstly, need inject Http:
import { Http } from '@angular/http'; ... @Injectable() export class DataService { ... constructor(private http: Http) { } ... |
Then implement getCustomers() function:
... getCustomers(): Promise<Customer[]> { return this.http.get(this.customersUrl) .toPromise() .then(response => response.json() as Customer[]) .catch(this.handleError); } ... |
See the signature of http get() function:
get(url: string, options?: RequestOptionsArgs): Observable<Response>; |
-> get() returns an Observable.toPromise()
function.
– response object is a string with json form, so we should transform it to JSON object by using response.json()
.
– .catch()
is used to handle errors when processing, and we should always implement it to handle exceptions.
DataService’s full sourcecode:
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Customer } from './customer'; @Injectable() export class DataService { private customersUrl = 'api/customer'; // URL to web API constructor(private http: Http) { } // Get all customers getCustomers(): Promise<Customer[]> { return this.http.get(this.customersUrl) .toPromise() .then(response => response.json() as Customer[]) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('Error', error); // for demo purposes only return Promise.reject(error.message || error); } } |
2. Create a SpringBoot RestApi Service
– Using SpringToolSuite, create a SpringBoot project. Then add web dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
– Create a Customer model:
package com.javasampleapproach.restful.model; public class Customer { private int id; private String firstname; private String lastname; private int age; public Customer(int id, String firstname, String lastname, int age){ this.id = id; this.firstname = firstname; this.lastname = lastname; this.age = age; } // id public void setId(int id){ this.id = id; } public int getId(){ return this.id; } // firstname public void setFirstname(String firstname){ this.firstname = firstname; } public String getFirstname(){ return this.firstname; } // lastname public void setLastname(String lastname){ this.lastname = lastname; } public String getLastname(){ return this.lastname; } // age public void setAge(int age){ this.age = age; } public int getAge(){ return this.age; } } |
– Create a simple RestController with 2 RequestMappings:
package com.javasampleapproach.restful.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.javasampleapproach.restful.model.Customer; @RestController @RequestMapping(value="/api") public class WebController { private Map<Integer, Customer> customers = new HashMap<Integer, Customer>(){ { put(1, new Customer(1, "Mary", "Taylor", 24)); put(2, new Customer(2, "Peter", "Smith", 18)); put(3, new Customer(3, "Lauren", "Taylor", 31)); } }; @GetMapping(value="/customer", produces=MediaType.APPLICATION_JSON_VALUE) public List<Customer> getAll(){ List<Customer> results = customers.entrySet().stream() .map(entry ->entry.getValue()) .collect(Collectors.toList()); return results; } } |
3. Integrate Angular App and SpringBoot Server
Angular4-Client and SpringBoot server work independently on ports 8080 and 4200.
Goal of below integration: the client at 4200 will proxy any /api requests to the server.
Step to do:
– Create a file proxy.conf.json under project angular4client folder with content:
{ "/api": { "target": "http://localhost:8080", "secure": false } } |
– Edit package.json file for “start” script:
... "scripts": { "ng": "ng", "start": "ng server --proxy-config proxy.conf.json", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ... |
>>> More details at: How to integrate Angular 4 with SpringBoot Web App and SpringToolSuite
4. Run & Check results
Build and Run the SpringBoot project with commandlines: mvn clean install
and mvn spring-boot:run
Run the Angular App with command: npm start
Make a request: http://localhost:4200/
, results:
– Response’s data:
– Customer List:
– Customer Details:
IV. Sourcecode
AngularHttpClient
SpringBootAngularHttpGet
Last updated on August 29, 2017.
hello…, how to deploy this? one jar?
To Deploy SpringBoot server with Angular4 client
Firstly, You build angularclient with command
ng build -prod
We have 2 approaches to deployment SpringBoot server with angular4 client:
–> Manually copy all files from dist folder to /src/main/resources/static folder of SpringBoot server project.
–> Using Maven plugin maven-resources-plugin to copy all files from dist folder to /src/main/resources/static folder of SpringBoot server project.
See details at: https://grokonez.com/spring-framework/spring-boot/integrate-angular4-springboot-web-app-springtoolsuite
Please be noticed that we had made a supporting video guide: https://youtu.be/Ps-7ZV8YpI0.