Angular 8/9 Promises Example – Manage HTTP Requests

By Digamber Rawat Last updated on
In this Angular 8/9 Promise tutorial, we are going to learn how to manage asynchronous HTTP response with JavaScript Promise objects.

Get the full code of this tutorial on the following GitHub repo:

Git Repo

Introduction to JavaScript Promise

Promises in ECMAScript are very much identical to the promises we make in our daily life. As per the general term, a promise is a commitment or guarantee by someone to do or not do something.

It goes the same with JavaScript promises, we define a promise object, and its provides the surety that it will return something in the future. A promise object works only once. Either It will be succeeded or failed, but it won’t work twice.

Since JavaScript is a synchronous programming language. But the right thing for the developers is we can make JavaScript Asynchronous using callback functions. A callback function can also be attached to the Promise’s fulfilled or rejected state to reveal the purpose of success or rejection.

Promises are always keen to be invoked. Still, if you want some laziness, then you must try RxJS observables. Check out my detailed article on handling HTTP requests with RxJS Observables in Angular 2+.

Creating JavaScript Promise is Easy

Setting up a Promise in JavaScript is easy using the ECMAScript 6 API. In the below Promise example, resolve will be called after 1.5 seconds.

const promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('Promise returns after 1.5 second!');
  }, 1500);
});

promise.then(function(value) {
  console.log(value);
  // Promise returns after 1.5 second!
});

We defined the Promise object with a new keyword and It is also knows as constructor. A Promise constructor is meant to be the executor, and It takes two parameters resolve and reject.

The resolve() function is invoked when the asynchronous task is completed and renders the result of the assigned tasks. In our case, we declared the setTimeout method, this timer function will be invoked after 1.5 seconds.

The second function is a reject() function, which is invoked when the assigned task gets failed and returns the reason with the error object.

Promise has three probable states:

  • Pending: Initial state, neither fulfilled nor rejected
  • Fulfilled: onFulfilled() will be invoked, corresponds to resolve()
  • Rejected: onRejected() will be invoked, corresponds to reject()

Angular 8/9 Promises Example with HttpClient API

In this section, we are going to look at how to use Promises in Angular 8/9 to manage the HTTP response asynchronously.

Open your Angular project in your favorite code editor and then go to app.module.ts file and import HttpClientModule service. Then also register it inside the imports array.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from "@angular/common/http";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Next, go to app.component.ts file. Here we will write the core logic to make the HTTP GET request and manage the response using the ES6 Promise in Angular 8/9.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

class Post {
  constructor(
    public userId: number,
    public id: string,
    public title: string,
    public body: string
  ) { }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

The OnInit lifecycle hook helps in performing any task when the component is ready.

The HttpClient API allows to handle the HTTP requests such as GET, POST, PUT, Update and Delete.

Post class has the Post data type information, map this class to the HTTP GET request.

export class AppComponent implements OnInit {

  api: string = "https://jsonplaceholder.typicode.com/posts";
  data = [];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getPosts();
  }

  getPosts() {
    const promise = new Promise((resolve, reject) => {
      const apiURL = this.api;
      this.http
        .get<Post[]>(apiURL)
        .toPromise()
        .then((res: any) => {
          // Success
          this.data = res.map((res: any) => {
            return new Post(
              res.userId,
              res.id,
              res.title,
              res.body
            );
          });
          resolve();
        },
          err => {
            // Error
            reject(err);
          }
        );
    });
    return promise;
  }

}

Set post API in an api: string variable and also declare data array. In data array we will render Promise response and display on the front-end.

Next, we injected the HttpClient inside the constructor using the private property.

Declare getPosts() custom function inside this function use Promise to fetch the posts data.

We declared the promise instance in the Angular custom method with new keyword and passed the resolve and reject method in it.

We set up the apiURL in the getPosts function and made the Http Get request followed by the toPromise() method. It converts basic observable to promise, we are getting the response and inserting inside the data array and then called the resolve() method. We also called the reject() method, and it will get the error object when the request gets failed.

Finally, we invoked the this.getPosts() function in the ngOnInit() lifecycle hook and in next step we will display the data on the front-end.

Next, go to app.component.html file and add the following code inside of it to show the posts data on the browser.

<table class="table table-striped">
    <thead>
        <tr class="table-info">
            <th scope="col">#</th>
            <th scope="col">UID</th>
            <th scope="col">Title</th>
            <th scope="col">Body</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let result of data">
            <th scope="row">{{result.id}}</th>
            <td>{{result.userId}}</td>
            <td>{{result.title}}</td>
            <td>{{result.body}}</td>
        </tr>
    </tbody>
</table>

We showed the data using *ngFor Angular loop inside the HTML table element.

Angular 8/9 Promises Example with HTTP

Conclusion

Finally, we have completed the Angular 8/9 Promises tutorial with an example. In this tutorial, we explored how to manage HTTP requests with JavaScript promises in an Angular app.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.