What Is Promise In Angular?

A Promise in Angular is a JavaScript object that represents the eventual completion (or failure) of an asynchronous action and allows us to handle the outcome once it is ready.

Promises are widely used in Angular to manage asynchronous tasks like HTTP requests, when we don’t know when the server will answer and don’t want to block the UI while waiting.

Here’s an example of utilising an Angular Promise to perform an HTTP request:

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’re utilising the @angular/common/http module’s HttpClient service to perform an HTTP GET request to a JSON placeholder API. The toPromise() function is then used to transform the Observable returned by the get() method into a Promise. Lastly, we’re handling the response and any issues with the.then() and.catch() methods.

When the Promise is resolved (i.e., when we receive a response from the server), the then() function is called, and when the Promise is refused, the catch() method is executed (i.e., when there is an error). In this example, we’re updating the component’s data property to the title field of the response object we received from the server.

Submit a Comment

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

Subscribe

Select Categories