We will create a REST web service application using Spring Boot and a client application using Angular 2. REST web service will expose methods for create, read, update and delete operation. The Angular application will use Angular Http API for CRUD operation. If our client application is running on different domain from web service domain, then the Spring Boot web service controller will configure client domain URL using @CrossOrigin annotation to handle Cross-Origin-Resource-Sharing (CORS). In our Spring Boot application, we will configure database using application.properties file. To interact with database we will use JPA EntityManager.

There are back-end application using spring-boot rest api and front-end application using Angular 2.

1-Complete REST Web Service Application using Spring Boot with Maven 

@CrossOrigin annotation handles Cross-Origin-Resource-Sharing (CORS). This annotation can be used at class level as well as method level in RESTful Web service controller. In our example Angular project will run on following URL.

http://localhost:4200 
And REST webs service project will run on following URL.

http://localhost:8080 
To allow our Angular project script to hit the web service we need to configure @CrossOrigin as follows

@CrossOrigin(origins = {"http://localhost:4200"}) 
We are using it at class level so that all the REST web service method will be available to our Angular application.

Create Java Main Class to Run Spring Boot Application

Create a java class with main() method that will call SpringApplication.run() to run the application.
MyApplication.java

package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {  
    public static void main(String[] args) {
 SpringApplication.run(MyApplication.class, args);
    }       
} 
We need to annotate above class with @SpringBootApplication that is equivalent to @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.

Run REST Web Service using Spring Boot

mvn spring-boot:run
or:

java -jar target/spring-boot-demo-0.0.1-SNAPSHOT.jar 

2-Complete Client Application using Angular 2 with TypeScript

We will create complete client application using Angular 2 with TypeScript.

 Run Angular 2 Application using Angular CLI

To run the angular application, find the following steps.
1. Install Angular CLI QUICKSTART using the link.
2. Download Angular project source code using download link given on this page in download section.
3. In your angular CLI application, replace src folder by the downloaded one.
4. Run ng serve command.
5. Our Angular application is ready on the following URL.
http://localhost:4200
a. Find the print screen when creating article. We will get validation messages when we click on CREATE button without entering data.
Enter the data in the form fields and click on CREATE button to create the new article.

b. When we click on EDIT button, we load article in form fields to update. Find the print screen. Click on UPDATE button to update the article for the given article id. By clicking on Go Back button we can return back to CREATE screen. Using DELETE button we can delete the article.

HTTP URLs, Methods and Response Status Code for CRUD Operation

We will use following HTTP URLs, methods and response status code for CRUD operation in our example.
1. Create :
REST Method: POST, URL: /user/article
Angular API: Http.post()
HTTP Response Status Code: 201 CREATED and 409 CONFLICT

2. Read :
REST Method: GET, URL: /user/article?id={id} (Fetches article by id)
REST Method: GET, URL: /user/all-articles (Fetches all articles)
Angular API: Http.get()
HTTP Response Status Code: 200 OK

3. Update :
REST Method: PUT, URL: /user/article
Angular API: Http.put()
HTTP Response Status Code: 200 OK

4. Delete :
REST Method: DELETE, URL: /user/article?id={id}
Angular API: Http.delete()
HTTP Response Status Code: 204 NO CONTENT

 Create Operation using Angular 2 Http.post()

We will perform create operation using Angular Http.post() method. It hits the request URL using HTTP POST method. Http.post() method syntax is as follows.

post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> 
The description of parameters is given as below.
url: This is the REST web service URL to create article.
body: This is of any type object that will be passed to REST web service server. In our example we will create an Angular class as Article and pass its instance to body parameter.
options: This is optional. This accepts the instance of Angular RequestOptions that is instantiated using Angular RequestOptionsArgs. Using RequestOptions we pass request parameter, request headers etc.

Http.post() returns instance of Observable. Observable is a representation of any set of values over any amount of time.
Client Code
Find the client code to create the article. Here we will use Angular Http.post() method.

articleUrl = "http://localhost:8080/user/article";
createArticle(article: Article):Observable<number> {
    let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: cpHeaders });
    return this.http.post(this.articleUrl, article, options)
        .map(success => success.status)
        .catch(this.handleError);
} 
We are passing header Content-Type as application/json. After successful operation we are returning status code as an instance of Observable.
Server Code
Find the web service method for create operation.

@PostMapping("article")
public ResponseEntity<Void> createArticle(@RequestBody Article article, 
UriComponentsBuilder builder) {
   boolean flag = articleService.createArticle(article);
   if (flag == false) {
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
   }
   HttpHeaders headers = new HttpHeaders();
   headers.setLocation(builder.path("/article?id={id}")
                              .buildAndExpand(article.getArticleId()).toUri());
   return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
} 
In the above code Article is a java entity that is equivalent to Angular Article class. @PostMapping is request mapping for HTTP POST method. When the process is successful, it returns HTTP status 201 CREATED and URL for new article in location header. If the article already exists then the above server code will return HTTP status 09 CONFLICT

Read Operation using Angular 2 Http.get()

We will perform read operation using Angular Http.get() method. It hits the URL using HTTP GET method. Find its syntax.

get(url: string, options?: RequestOptionsArgs) : Observable<Response> 
Find the description of the parameters.
url: Web service URL to read article.
options: This is optional. It is used to pass request parameter, headers etc.

Http.get() returns the instance of Observable.

Client Code
Find the Angular code using Http.get() that will pass request parameter to filter the result.

articleUrl = "http://localhost:8080/user/article";    
getArticleById(articleId: string): Observable<Article> {
   let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
   let cpParams = new URLSearchParams();
   cpParams.set('id', articleId);   
   let options = new RequestOptions({ headers: cpHeaders, params: cpParams });
   return this.http.get(this.articleUrl, options)
    .map(this.extractData)
    .catch(this.handleError);
} 
The above code will fetch an article for the given id.
Now find the client code using angular that will fetch all articles from the server.

allArticlesUrl = "http://localhost:8080/user/all-articles";
getAllArticles(): Observable<Article[]> {
    return this.http.get(this.allArticlesUrl)
 .map(this.extractData)
        .catch(this.handleError);
} 

Server Code
Find the web service method that will accept request parameter to filter the result.

@GetMapping("article")
public ResponseEntity<Article> getArticleById(@RequestParam("id") String id) {
   Article article = articleService.getArticleById(Integer.parseInt(id));
   return new ResponseEntity<Article>(article, HttpStatus.OK);
} 
@GetMapping is the request mapping for the HTTP GET method. It accepts the article id as request parameter that is used to fetch article by id. On successful operation it will return the article for the given id and HTTP status code 200 OK.
Now find the web service method that will return all articles.

@GetMapping("all-articles")
public ResponseEntity<List<Article>> getAllArticles() {
 List<Article> list = articleService.getAllArticles();
 return new ResponseEntity<List<Article>>(list, HttpStatus.OK);
} 
On successful operation it will return all articles and HTTP status code 200 OK.

Update Operation using Angular 2 Http.put()

We will perform update operation using Angular 2 Http.put() method. It hits the URL using HTTP PUT method. Find its syntax.

put(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> 
Find the description of parameters.
url: This is the REST web service URL to update article.
body: This is of any type object that will be passed to REST web service server. In our example we will create an Angular class as Article and pass its instance to body parameter. The instance of Article will have article id on the basis of which other fields of article will be updated.
options: This is optional. This is used to pass request parameter, request headers etc.

Http.put() returns the instance of Observable.
Client Code
Find the angular code that is using Http.put() method to update the article.

articleUrl = "http://localhost:8080/user/article";
updateArticle(article: Article):Observable<number> {
    let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: cpHeaders });
    return this.http.put(this.articleUrl, article, options)
          .map(success => success.status)
          .catch(this.handleError);
} 
In our Angular application we have created a class as Article and we are passing its instance to Http.put() method. The article will be updated on the basis of article id which is a field of our Angular Article class.
Server Code
Find the web service method to update the article.

@PutMapping("article")
public ResponseEntity<Article> updateArticle(@RequestBody Article article) {
 articleService.updateArticle(article);
 return new ResponseEntity<Article>(article, HttpStatus.OK);
} 
In the above code Article is a java entity that is equivalent to Angular Article class. @PutMapping is the request mapping with HTTP PUT method. On successful operation, the HTTP status 200 OK is returned.

Delete Operation using Angular 2 Http.delete()

We will perform delete operation using Angular Http.delete() method. Http.delete() hits the URL using HTTP DELETE method. Find its syntax.

delete(url: string, options?: RequestOptionsArgs) : Observable<Response> 
Find the description of the parameters.
url: Web service URL to delete article.
options: This is optional. It is used to pass request parameter, headers etc.

Http.get() returns the instance of Observable.
Client Code
Find the client code using Http.delete() method to delete article by id.

articleUrl = "http://localhost:8080/user/article";
deleteArticleById(articleId: string): Observable<number> {
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
     let cpParams = new URLSearchParams();
     cpParams.set('id', articleId);   
     let options = new RequestOptions({ headers: cpHeaders, params: cpParams });
     return this.http.delete(this.articleUrl, options)
    .map(success => success.status)
    .catch(this.handleError);
} 
In the request parameter we are passing article id to delete the article.
Server Code
Find the web service method that will delete the article for the given article id as request parameter.

@DeleteMapping("article")
public ResponseEntity<Void> deleteArticle(@RequestParam("id") String id) {
 articleService.deleteArticle(Integer.parseInt(id));
 return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
} 
On successful operation the HTTP status code 204 NO CONTENT is returned.

References

Angular Http
Spring Boot REST + JPA + Hibernate + MySQL Example
Angular 2 Http get() Parameters + Headers + URLSearchParams + RequestOptions Example
Angular 2 Http post() Example

Download Source Code

Angular 2 Application
OR from
spring-boot-rest-angular-2-jpa-hibernate-mysql-crud

By Arvind Rai, May 24, 2017