Angular 14 Promise Tutorial with HTTP Request Example

Angular TypeScript Promise tutorial, through this comprehensive guide you will learn how to handle HTTP requests using JavaScript Promise object in an Angular application in conjunction with HttpClient class.

Introduction to JavaScript Promise

In JavaScript Promise is an object which produces or manifests the value subsequently; a promise mechanism implied three presumable states, those states are pending, fulfilled, and rejected.

  • pending – Not yet rejected likewise fulfilled.
  • fulfilled – The operation related to promise completed.
  • rejected – The operation concerned to the Promise failed.

Create TypeScript Promise

Here is the simple JavaScript promise example that displays a message in conjunction with resolve method:

let promise = new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve('Executes after 2 seconds');
  }, 1500);
});

promise.then((success) => { 
        console.log(success); 
    })
    .catch((error) => { 
        console.log(error); 
    });

// result: Executes after 2 seconds

The promise object is declared with resolve and reject parameters. The resolve method executes on the successful task completion in conjunction with then() and catch() methods.

Within the then() method, you can declare 2 callback functions and execute right after a promise is resolved or rejected.

Similarly, in catch() method, you can declare one callback function; it executes when the promise is failed, or an error occurs somehow.

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Handle HTTP Requests in Angular 13 with TypeScript Promise

We have seen the nitty-gritty of TypeScript/JavaScript Promise object; now, you will ascertain how to handle asynchronous HTTP requests using Promise in Angular.

First, you need to install a basic angular project executing the provided command:

ng new angular-promise-demo

Move inside the app’s root:

cd angular-promise-demo

Next, the task is to head over to the app.module.ts file. Next, import HttpClientModule from “@angular/common/http”
the package on top of that, add it into 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 { }

Open and update provided code in app.component.ts file:

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

class User {
  constructor(
    public id: number,
    public name: string,
    public username: string,
    public email: string
  ) { }
}

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

export class AppComponent implements OnInit {

  API: string = "https://jsonplaceholder.typicode.com/users";
  USERS = [];

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.usersList();
  }

  usersList() {
    const promise = new Promise((resolve, reject) => {
      const endpoint = this.API;
      this.httpClient
        .get<User[]>(endpoint)
        .toPromise()
        .then((res: any) => {
          this.USERS = res.map((response: any) => {
            return new User(
              response.id,
              response.name,
              response.username,
              response.email
            );
          });
          resolve();
        }, error => {
            reject(error);
          }
        );
    });
    return promise;
  }

}

As shown in the example, a demo API holds the users’ list; we make the HTTP GET request and handle the users’ data with the Promise object.

Here the user’s data is fetched from the server and displayed into the HTML table on successful operation with resolve() method. If somehow an error occurred, then the reject() method will be invoked.

Open app.component.html file, likewise update the suggested code within:

<table class="table">
  <thead>
    <tr class="table-primary">
      <th>#Id</th>
      <th>Name</th>
      <th>Username</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of USERS">
      <th scope="row">{{user.id}}</th>
      <td>{{user.name}}</td>
      <td>{{user.username}}</td>
      <td>{{user.email}}</td>
    </tr>
  </tbody>
</table>

Conclusion

Eventually, the Angular HTTP Promise example tutorial is over; in this tutorial, we learned about JavaScript Promise and its working structure.

Not just that, we also learned to make asynchronous HTTP requests with Promise object in angular by example.