DEV Community

Ahmed
Ahmed

Posted on • Edited on

Angular 14 Promise by Example

In this tutorial, we'll learn about JavaScript promises and we'll see how to use them by example with Angular 14 and HttpClient.

Read the original post from Angular 14 Promises example.

What's a JavaScript Promise?

A promise is a JavaScript object that may produce a value at some point in time. A promise may be in one of 4 possible states: fulfilled, rejected, pending or settled.

Promises simplify deferred and asynchronous computations. A promise represents an operation that hasn't completed yet. Source

A promise can be:

  • fulfilled - The action relating to the promise succeeded
  • rejected - The action relating to the promise failed
  • pending - Hasn't fulfilled or rejected yet
  • settled - Has fulfilled or rejected

This is an example of promise in plain JavaScript:

var promise = new Promise((resolve, reject) => { 
    resolve("Promise Resolved"); 
}) 

promise.then((success) => { 
        console.log(success); 
    }) 
    .catch(function(error) => { 
        console.log(error); 
    }); 
// Output: Promise Resolved
Enter fullscreen mode Exit fullscreen mode

Promises can be executed by calling the then() and catch() methods.

The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected.

The catch() method takes one callback function and is invoked when an error occurs.

Promises with TypeScript and Angular 14 by Example

Let's now see how to use Promises in Angular 14 to work with HTTP asynchronously.

Head back to a folder where you want to create your project. Next open a command line interface and run the following command:

$ ng new angular14promises --routing=false --style=css
Enter fullscreen mode Exit fullscreen mode

This will create a new Angular 14 application with no routing and CSS for stylesheets format.

Now open the src/app/app.module.ts file and import HttpClientModule and add it inside the imports array as follows:

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]
})
Enter fullscreen mode Exit fullscreen mode

Next, open the src/app/app.component.ts file and add the following code to send an HTTP GET request and process the response using a Promise.

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "Angular 10 and Promises Example";

  API_KEY = "e40d07f00b094602953cc3bf8537477e";

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    console.log("Angular 10 Promises");
    this.fetchDataAsPromise()
      .then((data) => {
        console.log(JSON.stringify(data));
      })
      .catch((error) => {
        console.log("Promise rejected with " + JSON.stringify(error));
      });
  }

  fetchDataAsPromise() {
    return this.httpClient
    .get(
        `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
      )
      .toPromise();
  }
}
Enter fullscreen mode Exit fullscreen mode

We import HttpClient and inject it via the component constructor and use it to send the HTTP request.

Next, we call the get() method to send the request and the toPromise() method to convert the returned RxJS Observable to a promise.

  fetchDataAsPromise() {
    return this.httpClient
    .get(
        `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`
      )
      .toPromise();
  }
Enter fullscreen mode Exit fullscreen mode

In the ngOnInit() life-cycle method, we send the actual request by calling the then() method of the promise as follows:

    this.fetchDataAsPromise()
      .then((data) => {
        console.log(JSON.stringify(data));
      })
      .catch((error) => {
        console.log("Promise rejected with " + JSON.stringify(error));
      });
Enter fullscreen mode Exit fullscreen mode

If the promise is resolved successfully we simply output the data in the console and in case of an error we display the error.

In plain JavaScript, you can send http requests with the JavaScript Fetch API.

Conclusion

We have seen how JavaScript promises are used with Angular 10 by example and how to make asynchronous operations such as HTTP requests instead of observables.

Top comments (1)

Collapse
 
bias profile image
Tobias Nickel

I would hope more angular engineers would do the step to promises and async/await.

Because I often see bugs of duplocate listen on a subscription or simply listen on a steam that is guarantied to have only one event because it is an http request, going in and out, that`s it.