Angular 4 Rest Api With Http Request In 5 Minutes

2

Same as Angular 1.x and 2.x, Angular 4 provides HTTP service to call rest API. By using HTTP, we can perform or call the Angular 4 rest API with HTTP requests.

This page will guide you over how we can use HTTP request in Angular 4 to communicate with the database and can do the required database operations.

What is HTTP request?

First of all, HTTP is an injectable class, with the methods that help us to perform HTTP requests.

In SPA (Single Page Applications), generally HTTP requests are used to call the rest API to perform the database operations from the front-end.

Use of Angular 4 REST API with HTTP request

HTTP is lives in the @angular/http module along with lot more methods that can be useful for us while using HTTP requests.

1. Import HttpModule in AppModule to use it in our app.

//Import browser module
import { BrowserModule } from '@angular/platform-browser'; 
//Import HTTP modules
import { Http, Response, RequestOptions, Headers } from '@angular/http';

@NgModule({
---------
  imports: [     
        BrowserModule,
	HttpModule
  ]
---------
})

2. Inject the Http in constructor of the class to use it in our class.

constructor(private http:Http) { } 

3. Now, we can use this.http with http request methods.

this.http.post(this.url, book, options); 

IMO, we should use HTTP requests in an injectable service. So, whenever we require HTTP REST API calls, we just need to use that service in our component and that’s it.

Here, is an ideal example of service that performs Angular 4 REST API with HTTP request.

//Import Injectable
import { Injectable } from '@angular/core';
//Import HTTP modules
import {  Http, Response, Headers } from '@angular/http';
//Import Observable
import { Observable } from 'rxjs';
import 'rxjs/Rx';

@Injectable()
export class DbOperationsService{

	constructor(private http: Http){}

	saveToDb(toDoList: any[]){
		return this.http.put('https://HOST/list.json', toDoList);
	}

	getDb() {
		const headers = new Headers();
                headers.append('Access-Control-Allow-Origin', '*');
                return this.http.get('https://HOST/list.json', {headers: headers});
	}
}

Types of HTTP request in Angular 4

We can use a specific type of request in HTTP from the list of following.

  • GET
    doGET() {
      console.log("GET");
      let url = `${this.apiRoot}/get`;
      this.http.get(url).subscribe(res => console.log(res.text())); 
    }
    
  • POST
    doPOST() {
      console.log("POST");
      let url = "{URL}/POSTMethod";
      this.http.post(url, {moo:"foo",goo:"loo"}).subscribe(res => console.log(res.json()));
    }
    
  • PUT
      console.log("PUT");
      let url = "${URL}/${hero.id}";
      return this.http
                 .put(url, JSON.stringify(hero), {headers: headers})
                 .map(res => res.json());
    
  • DELETE
    delete(url: string, options?: RequestOptionsArgs): Observable<Response>
    

Here, as you seen we have used Observables.

Observables can help us to manage the asynchronous data, such as data coming from a backend. And that can be used by importing the library called Reactive Extensions (RxJS).
And Observables are a proposed feature for ES2016, the next version of JavaScript.

To conclude,

Here is a list of things that we’ve convered,

  • We have gone through and understand the HTTP request.
  • How we can use HTTP request in Angular 4 for calling REST API.
  • Also, we have gone through the list of available methods of HTTP request.
  • Plus, we’ve created an injectable service that contains REST API to use in our app

In SPA, the HTTP is useful for us whenever we want to connect with the backend and able to do the database manipulation using REST API.

One more thing, we should take care is the security, when we use SPA with REST API, we should have authentication token generated by backend on every request.

That way we can make sure the requests are secured and by the authenticated users only, Example on Session Management In Angular 4

Suggested visit,

Finally, I hope you love this article.

Feel free to share your inestimable suggestions/feedback by commenting below.

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Mohit Tanwanimike wassermann Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
mike wassermann
Guest
mike wassermann

Where can I get the code?