Home  >  Angular 2

Angular 2 Http post() Example

By Arvind Rai, April 16, 2017
On this page we will provide angular 2 Http post() example. It performs a request using HTTP POST method. In Http.post() method, we need to pass server URL, any object to post and request option that is optional. In request option we can set request headers such as content type and to handle this angular provides Headers and RequestOptions API. Headers class is used to create request header and RequestOptions is used to create request option using headers, credentials etc. Http.post() method returns the instance of Observable of Response type. Using angular Response we can access response status, headers etc. On this page we will provide the example in which we will use Http.get() and Http.post using Observable and Promise both. For testing purpose we are using angular in-memory web API to get and post data. In our example we will fetch the book details using Http.get(). We will take user input for new book details and that we will post using Http.post method. To test Http.post in our example, we will use angular in-memory web API that will provide a test URL to post data. In real time we need to use actual REST web service URL. Now find the complete example step by step.

Software Used

Find the software used in our example.
1. Angular 4.0.0
2. TypeScript 2.2.0
3. Node.js 6.10.1
4. Angular CLI 1.0.0
5. Angular Compiler CLI 4.0.0

Http.post()

Http.post() performs a request using HTTP POST method. Find the syntax.
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> 
url: This is HTTP URL using which we post data to the server.
body: This is the object which we need to post to the server.
options: This is optional. Here we pass the instance of RequestOptionsArgs that uses headers.
Observable<Response>: This is the return type of Http.post().

To use Http.post(), we need to follow below steps.
Step-1:: First step is that we need to configure HttpModule in imports metadata of @NgModule decorator in our application module.
import { BrowserModule } from '@angular/platform-browser'; 
import { HttpModule } from '@angular/http';

@NgModule({
---------
  imports: [     
        BrowserModule,
	HttpModule
  ]
---------
}) 
Step-2:: We should perform server communication in a service class and not in component. This approach is preferable by design. In a service class we will use dependency injection to get the instance of angular Http as given below.
constructor(private http:Http) { } 
Step-3:: Now we are ready to use http.post() as follows.
Observable<Response> ob = this.http.post(this.url, book, options); 
http.post() returns instance of Observable that can be later subscribed to get result.

Angular In-Memory Web API

Angular provides in-memory web API to process HTTP request in test environment. In case we don't have actual server URL, we can use angular in-memory web API for testing our angular Http methods. It provides a dummy URL that can be replaced by actual REST web service URL later. It returns an Observable of HTTP Response object in the manner of a RESTy web api. In our example we are using in-memory web API to get and post data. To use it in our angular application we need to follow below steps.
Step-1: Add angular-in-memory-web-api in dependencies block in package.json file as given below.
"angular-in-memory-web-api": "~0.3.0" 
Step-2: Run npm install command to download angular-in-memory-web-api.
Step-3: Create a class implementing InMemoryDbService interface. In our example we are creating an in-memory DB for books. Find our class for our in-memory DB.
book-data.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';

export class BookData implements InMemoryDbService {
  createDb() {
    let books = [
      { id: 1, name: 'Core Java' },
      { id: 2, name: 'Angular 2' },
      { id: 3, name: 'Hibernate' }
    ];
    return {books};
  }
} 
To interact with DB, URL will be api/books .
Step-4: Before using DB we need to configure our above class in application module using imports metadata of @NgModule as follows.
InMemoryWebApiModule.forRoot(BookData) 
Find the application module.
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { BookData } from './book-data';

@NgModule({
---------
  imports: [     
        BrowserModule,
	HttpModule,
	InMemoryWebApiModule.forRoot(BookData)
  ]
---------
}) 
Find the link for more information on in-memory web API.

For testing our Angular Http methods, we can also use JSON-Server.

Http.post with Observable

Find the code snippet to use Http.post with Observable.
addBookWithObservable(book:Book): Observable<Book> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, book, options)
               .map(this.extractData)
               .catch(this.handleErrorObservable);
} 
Headers: This is angular class to create header. In our example we are passing request header content type as application/json.
RequestOptions: It creates a request option object which we need to optionally pass in http.post().

We are posting book object to http.post() method that will return Observable<Response>. Using RxJS map() method we convert response data into JSON and finally we get Observable<Book> instance.

Http.post with Promise

Find the code snippet to use Http.post with Promise.
addBookWithPromise(book:Book): Promise<Book> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, book, options).toPromise()
           .then(this.extractData)
           .catch(this.handleErrorPromise);
} 
Using RxJS toPromise() method we convert Observable<Response> into Promise<Response>. Inside then() method, response data is converted into JSON. then() method again returns Promise and hence we finally get Promise<Book> instance.

Complete Example

Now find the complete example.
book.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { Book } from './book';

@Injectable()
export class BookService {
    url = "api/books";
    constructor(private http:Http) { }
    getBooksWithObservable(): Observable<Book[]> {
        return this.http.get(this.url)
		   .map(this.extractData)
		   .catch(this.handleErrorObservable);
    }
    addBookWithObservable(book:Book): Observable<Book> {
	let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.url, book, options)
                   .map(this.extractData)
                   .catch(this.handleErrorObservable);
    }
    getBooksWithPromise(): Promise<Book[]> {
        return this.http.get(this.url).toPromise()
		    .then(this.extractData)
	            .catch(this.handleErrorPromise);
    }
    addBookWithPromise(book:Book): Promise<Book> {
	let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.url, book, options).toPromise()
	           .then(this.extractData)
                   .catch(this.handleErrorPromise);
    }		
    private extractData(res: Response) {
	let body = res.json();
        return body.data || {};
    }
    private handleErrorObservable (error: Response | any) {
	console.error(error.message || error);
	return Observable.throw(error.message || error);
    }
    private handleErrorPromise (error: Response | any) {
	console.error(error.message || error);
	return Promise.reject(error.message || error);
    }	
} 
book.ts
export class Book {
   id: number;
   name: string;
   constructor() { 
   }
} 
Find the component that is using Observable.
observable.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { BookService } from './book.service';
import { Book } from './book';

@Component({
   selector: 'app-observable',
   templateUrl: './observable.component.html',
   styleUrls: ['observable.component.css']
})
export class ObservableComponent implements OnInit { 
   books: Book[];
   errorMessage: String;
   bookName: String;
   book = new Book();   
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
        this.fetchBooks();
   }
   fetchBooks(): void {
        this.bookService.getBooksWithObservable()
	    .subscribe( books => this.books = books,
                        error => this.errorMessage = <any>error);    
   }
   addBook(): void {
     this.bookService.addBookWithObservable(this.book)
	     .subscribe( book => {
			            this.fetchBooks();		
                                    this.reset();   
		                    this.bookName = book.name;						   
			 },
                         error => this.errorMessage = <any>error);
   }
   private reset() {
           this.book.id = null;	 
	   this.book.name = null;
	   this.errorMessage = null;
	   this.bookName = null;
   }
} 
After adding book, we will fetch the books to display on UI. To ensure that we fetch books only after adding book, we should call fetchBooks() method inside subscribe() method of Observable returned by addBookWithObservable() method of our BookService . Now find the HTML template.
observable.component.html.
<h3>Book Details with Observable </h3>
<ul>
  <li *ngFor="let book of books" >
    Id: {{book.id}}, Name: {{book.name}}
  </li>
</ul>
<div>
  <div>
     <label>Id: </label>
     <input [(ngModel)]="book.id" />
  </div>
  <div>
     <label>Name: </label>
     <input [(ngModel)]="book.name" />
  </div>
  <div>
     <button (click)="addBook()">Add</button>
  </div>
</div> 
<div *ngIf="bookName" [ngClass] = "'success'"> {{bookName}} Added. </div>
<div *ngIf="errorMessage" [ngClass] = "'error'"> {{errorMessage}} </div> 
observable.component.css
.success{
    color: green;
    font-size: 20px;
}
.error{
    color: red;
    font-size: 20px;
} 
Find the component that is using Promise.
promise.component.ts
import { Component, OnInit } from '@angular/core';

import { BookService } from './book.service';
import { Book } from './book';

@Component({
   selector: 'app-promise',
   templateUrl: './promise.component.html',
   styleUrls: ['promise.component.css']   
})
export class PromiseComponent implements OnInit { 
   books: Book[];
   errorMessage: String;
   bookName: String;
   book = new Book();      
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
	this.fetchBooks();
   }
   fetchBooks(): void {
        this.bookService.getBooksWithPromise()
          .then( books => this.books = books,
                 error =>  this.errorMessage = <any>error);   
   }
   addBook(): void {
     this.bookService.addBookWithPromise(this.book)
	     .then( book => {
			      this.fetchBooks();		
                              this.reset();   
            		      this.bookName = book.name;					 
		    },
                    error => this.errorMessage = <any>error);
   }   
   private reset() {
           this.book.id = null;	 
	   this.book.name = null;
	   this.errorMessage = null;
	   this.bookName = null;
   }   
} 
After adding book, we will fetch the books to display on UI. To ensure that we fetch books only after adding book, we should call fetchBooks() method inside then() method of Promise returned by addBookWithPromise() method of our BookService . Now find the HTML template.
promise.component.html
<h3>Book Details with Promise </h3>
<ul>
  <li *ngFor="let book of books" >
    Id: {{book.id}}, Name: {{book.name}}
  </li>
</ul>
<div>
  <div>
     <label>Id: </label>
     <input [(ngModel)]="book.id" />
  </div>
  <div>
     <label>Name: </label>
     <input [(ngModel)]="book.name" />
  </div>
  <div>
     <button (click)="addBook()">Add</button>
  </div>
</div> 
<div *ngIf="bookName" [ngClass] = "'success'"> {{bookName}} Added. </div>
<div *ngIf="errorMessage" [ngClass] = "'error'"> {{errorMessage}} </div> 
promise.component.css
.success{
    color: green;
    font-size: 20px;
}
.error{
    color: red;
    font-size: 20px;
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		<app-observable></app-observable>
		<app-promise></app-promise>
             `
})
export class AppComponent { 

} 
app.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';

import { AppComponent }  from './app.component';
import { ObservableComponent }  from './observable.component';
import { PromiseComponent }  from './promise.component';
import { BookService } from './book.service';
import { BookData } from './book-data';

@NgModule({
  imports: [     
        BrowserModule,
	FormsModule,
	HttpModule,
	InMemoryWebApiModule.forRoot(BookData)
  ],
  declarations: [
        AppComponent,
	ObservableComponent,
	PromiseComponent
  ],
  providers: [
        BookService
  ],
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { } 

Test Application

To test the application, find following steps.
1. Download source code using download link given on this page.
2. In your angular CLI application, replace src folder.
3. Add angular-in-memory-web-api in dependencies block in package.json file.
4. Run npm install and then run ng serve .
5. Now access the URL http://localhost:4200 and add some books. Find the print screen.
Angular 2 Http post() Example


Find the link for Angular 2 Http CRUD operation with Spring Boot.

Spring Boot REST + Angular 2 + JPA + Hibernate + MySQL CRUD Example

Reference

HTTP CLIENT

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS





Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us