In this Angular tutorial, we will discuss how to make HTTP calls in Angular applications using JavaScript Promises.
JavaScript Promises
As we know JavaScript is a synchronous single-threaded programming language. Each statement executes after the previous task is completed. But with the help of callback functions, we can make JavaScript an asynchronous language.
A callback function is provided with a task to get completed based on some events triggered. In a similar way, we can create Promise objects to handle the Asynchronous tasks which ensure to return a value in form of callbacks.
Promises are committed to returning values in form of callbacks, either a success or a rejection.
How to Use Simple Promises in Angular
Let’s check a simple Promise example using JavaScript ES6.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Task will be done in 1 second');
}, 1000);
});
promise.then((value) => {
console.log(value); //OUTPUT Task will be done in 1 second
}, (error) => {
console.log(error); // Error triggered when reject() is returned.
});
The new keyword is used to create a Promise. A promise inject a function that takes resolve and reject as two parameters.
The resolve()
function is triggered when the asynchronous task assigned to the Promise is completed successfully. This task can be an HTTP Rest API call.
The reject()
function is triggered when an error is encountered while performing the Asynchronous task. In our example, we defined a setTimeout() function which is sure to get completed successfully in 1 second. But sometimes, Asynchronous tasks like HTTP calls may fail due to some server or network issue in that case the reject() callback is used to return an error.
A Promise is comprised of three states:
Pending
: When a promise is in its initial State, yet to be fulfilled or Rejected.Fulfilled
: Theresolve()
callback is returned as a success handler.Rejected
: Thereject()
callback is returned as an error handler.
Example of Angular Promises to Make HTTP REST call using HttpClient API
Now, we will trigger HTTP calls in Angular by using Promises and handle the Success and Error callbacks.
Step 1) Import the HttpClientModule
in AppModule
Open the app.module.ts file then import the HttpClientModule and update the imports array. The HttpClientModule is required to trigger HTTP calls from the Angular applications
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
.
Step 2) Update AppComponent to make HTTP call and handle responses using ES6 Promises
Now, open the app.component.ts file, then we will add code to make HTTP Get API request and handle the response using the ECMAScript Promise in Angular.
In the constructor, inject the HttpClient
service. Add a method getComments()
inside the ngOnInit()
hook.
// app.component.ts
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
apiUrl = 'https://jsonplaceholder.typicode.com/comments';
commentList:any[] = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.getComments();
}
getComments() {
const promise = this.http.get<[]>(this.apiUrl).toPromise();
return promise.then(
(response: any) => {
// Success callback
this.commentList = response;
},
(error: any) => {
// Error callback
console.log(error);
}
);
}
}
The ngOnInit() hook is triggered when the component is initialized. This hook is used to load all the required resources.
Inside the getComments() function, there is get()
method of HttpClient service after that we added toProvider()
to return a Promise instead of RxJS Observable.
The promise object returned is then used to handle the Success and Error callbacks inside then()
method.
Using then() and catch() to Handle Promises Response
We can also use the then()
and catch()
to handle the Success or Error callbacks as shown below
getComments() {
const promise = this.http.get<[]>(this.apiUrl).toPromise();
return promise.then(
(response: any) => {
// Success callback
this.commentList = response;
}
).catch((error: any) => {
// Error callback
console.log(error);
});
}
Step 3) Update App Component Template to Data
Last but not least, update the app.component.html file with a table to populate the data.
<h1>Comment List</h1>
<table>
<thead>
<tr>
<th>#</th>
<th>Comment ID</th>
<th>Name</th>
<th>Email</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let comment of commentList">
<th>{{comment.id}}</th>
<td>{{comment.postId}}</td>
<td>{{comment.name}}</td>
<td>{{comment.email}}</td>
<td>{{comment.body}}</td>
</tr>
</tbody>
</table>
Here we used *ngFor
Angular directive to iterate over the commentList
Array items which we fetched from remove API.
Conclusion
We discussed how to make Get HTTP call from the Angular application using the JavaScript Promises. Using Promises we can easily handle the Success and Error responses in very efficient ways. The toPromise()
we used to return a Promise object instead of Observable which is used by default in RxJS to handle HTTP calls.
Leave a Reply