Promises in Angular

A promise in Angular is a JavaScript object that allows us to handle the outcome as it becomes available and reflects the ultimate success (or failure) of an asynchronous action.

In order to manage asynchronous actions like HTTP requests, where we don’t know when the server will answer and we don’t want to block the UI while we wait for a response, promises are heavily utilised in Angular.

A Promise is used in Angular to send an HTTP request, as seen in the following example:

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

@Component({
    selector: 'app-root',
    template: '<h1>{{data}}</h1>'
})
export class AppComponent implements OnInit {
    data: string;
    constructor(private http: HttpClient) {}
    ngOnInit() {
        this.http.get('https://jsonplaceholder.typicode.com/todos/1').toPromise().then((response) => {
            this.data = response['title'];
        }).catch((error) => {
            console.log(error);
        });
    }
}

In this example, we’ll perform an HTTP GET call to a JSON placeholder API using the HttpClient service from the @angular/common/http module. The Observable produced by the get() function is then changed into a Promise by invoking the toPromise() method.

In order to handle the answer and any potential issues, we’re also utilising the.then() and.catch() methods.

The catch() function is invoked when the Promise is refused, and the then() method is performed when the Promise is resolved (i.e., when we receive a response from the server) (i.e., when there is an error).

In this example, we’re updating the component’s data property to the response object’s title field, which we get from the server.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories