Making API calls using HTTP in Angular applications

May 29, 2017
by Rahil Shaikh
  • HTTP in Angular

Web applications need to communicate to the server to fetch the data to be displayed to the end-user. In Stateless SPA this is done by calling a REST API or a web service over HTTP.

We have already seen in one of our earlier tutorial, how we can communicate to the server in Angular 1X.

In this tutorial, we will see how we can make an API call via HTTP in Angular 2+ applications.

Angular 1 provided us with the $http service similarly in Angular 2 we have the HTTP module. The main difference, however, is that asynchronous events like API call always returned a promise or a callback, but in the case of Angular, the HTTP service returns an observable.

There are various advantages of using observables over promises, observables are lazy and won’t be invoked unless specifically subscribed, observable provides multiple events thereby giving more control, observables are cancellable and provide a lot of useful operators like map, forEach, reduce, etc. Observables are like promises + events.

Catching Up

So in our previous tutorial, we had created a simple Angular Application crazy-quotes that would display our quote. So let’s continue on that and make our crazy-quotes application more Dynamic.

If you are following along from the previous tutorial, you can clone the repo, others can just read along to learn how HTTP requests are made in Angular Application.

$ git clone https://github.com/rahil471/crazy-quotes.git

We will use a public API provided by quotes.rest. This API will give us a daily random quote. So first let’s just test the API out.

GET: http://quotes.rest/qod

We are interested in the quote and the author.

Making an HTTP call

Now let’s remove our static quote and get one via a remote request.

First, we have to import the required modules. Open up the-quote.component.ts

/src/app/the-quote/the-quote.component.ts
import { Component, OnInit } from '@angular/core';
/** New imports below */
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

Also, note that HttpModule should be included under imports in your app.modules.ts. Angular CLI has already done this for us.

Now let’s make a request and fetch our quote. First, we will initialize the http variable as private. Then, in our ngOnInit function we will call our API. Remember, the http service in Angular by default returns an observable of which we have discussed earlier in the tutorial.

/src/app/the-quote/the-quote.component.ts
import { Component, OnInit } from '@angular/core';
/** New imports below */
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

@Component({
  selector: 'app-the-quote',
  templateUrl: './the-quote.component.html',
  styleUrls: ['./the-quote.component.css']
})
export class TheQuoteComponent implements OnInit {
  myQuote : any = {
    id: 1,
    quote: String,
    by: String
  }
  constructor( private http: Http) {
  }

  ngOnInit() {
    this.http.get('http://quotes.rest/qod').map((res : Response)=>{
      return res.json();
    })
    .catch((err: Response|any)=>{
      return Observable.throw(err.json());
    }).subscribe((data)=>{      
      this.myQuote.quote = data.contents.quotes[0].quote; //set our myQuote Object
      this.myQuote.by = data.contents.quotes[0].author; //set our myQuote Object
    }, (err)=>{
      console.log(err);
      this.myQuote.quote = "Error in fetching data"; //set our myQuote Object
      this.myQuote.by = "Error in fetching data"; //set our myQuote Object
    });
  }

}

Run the app with ng serve.

The Http Class

Here is an overview on the Http class..

Http Class
class Http {
constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions)
request(url: string|Request, options?: RequestOptionsArgs) : Observable<Response>
get(url: string, options?: RequestOptionsArgs) : Observable<Response>
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
put(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
delete(url: string, options?: RequestOptionsArgs) : Observable<Response>
patch(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
head(url: string, options?: RequestOptionsArgs) : Observable<Response>
options(url: string, options?: RequestOptionsArgs) : Observable<Response>
}

You can read more about it here.

Conclusion

This was the very basics of making HTTP requests in Angular applications. One might argue that HTTP requests should be moved to services and yes that is right, but we must learn one thing at a time. In our next tutorial, we will create an @Injectable service and move our HTTP request to it.

Further Links

  1. Learn Angular 2 From our Free Video Course on YouTube
  2. Learn Angular 2 by building 12 apps

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment