Making HTTP Calls Using Angular

HTTP Calls are very important and essential part of any application. In our previous tutorial, we covered how to get started with Angular2 using amazing angular command line tool.

In this tutorial, we are going to follow up on the previous tutorial and learn how to make HTTP calls using Angular 2.

If you haven’t already read the previous Angular 2 tutorial, click here to read ( It’s important ).

Getting Started

You need to have angular 2 command line tool installed along with Node.js and NPM. If it’s new to you, read this tutorial.

Create new Angular 2 project using the following command.

COMMAND
ng new <app-name>

Switch to the project folder and run the application.

COMMAND
cd <add-name> && ng serve

Visit localhost:4200 to view the app. You should see a similar screen as shown below.

Getting Started with Angular2

Moving on!

HTTP Calls in Angular 2

To use the Angular 2 Http module in our components, we have to first import the Http module.

After that, we can just inject it via Dependency Injection in the constructor.

To do so, create new file inside the /src/app/ folder called app.service.ts and paste the code shown below.

/src/app/app.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HackerNewsService {
  constructor (
    private http: Http
  ) {}
}

Now let’s add some function to perform HTTP calls.

/src/app/app.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HackerNewsService {
  constructor (
    private http: Http
  ) {}
 
  // Calling the Hackernews API using GET method.
  getNews() {
    return this.http.get(`https://hn.algolia.com/api/v1/search_by_date?query=node&tags=story`)
    .map((res:Response) => res.json());
  }
}

Angular 2 introduces new annotation to declare the class as Injectable. To read more about it in depth, visit the official documentation here.

In a nutshell, @Injectable annotation indicates that the class has dependencies that should be injected into the constructor when creating an instance of the class.

Another thing is that we are not using callbacks or promises in the HTTP calls. Instead what we are using is called Observables.

You can learn more about the Observables here.

Consuming the HTTP Services in Angular 2

To consume the Service, import it in component and module file and call the HTTP Services function from the component.

To do so, edit the /src/app/app.component.ts file. First import the Services class.

/src/app/app.component.ts
//importing the class

import { HackerNewsService } from './app.service';

Then, call the Services.

/src/app/app.component.ts
export class HackerNewsComponent {
  news = {};
  constructor(private HackerNewsService: HackerNewsService) {
    this.HackerNewsService.getNews().subscribe(data => this.news = data);
  }
  // You can also create the functions and consume services.
}

Next, you need to edit the /app/src/app.module.ts file.

First import the following modules.

/src/app/app.module.ts
import { HttpModule } from '@angular/http';
import { HackerNewsComponent } from './app.component';
import { HackerNewsService } from './app.service';

Then, add the Services in the providers array.

/src/app/app.module.ts
providers: [HackerNewsService]

This way you can call and consume HTTP Apis in Angular 2.

Calling POST method

To make HTTP Calls with the POST method, use this function.

CODE
  var headers = new Headers();
  headers.append('Content-Type', 'application/json');
  var body = {"userName": "shahid","password": "notgonnatellyou"};
  this.http
    .post('some-http-api', body, { headers: headers })
    .map(response => response.json());

Similarly, you can call PUT and DELETE method.

Further Reading

Conclusion

Angular2 HTTP calls with observables is really amazing enhancement. You can also convert the observables to promise, just to make things more clearer. We are coming up with more tutorials on Angular2, so make sure you have signup for our email newsletter.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126