Angular then() Method
We will introduce the then()
method and discuss promises
in Angular.
Use the then()
Method in Angular
The then()
is an Angular promise
method used as the second argument. The then()
method is only executed when the promise
is rejected.
To understand the then()
method in detail, we first have to learn about the promises
in Angular.
the promise
in Angular
When the applications were simpler, the callback functions were called immediately, but with the time when applications got complex and richer with JavaScript for modern browsers, callback became a hassle. Call back functions become slower and sometimes get stuck while requesting data.
As a solution in ES6
, promises
were introduced to solve the problems and simplify them. They are powerful abstractions for writing asynchronous functions better and are easy to maintainable.
A promise
is an API abstraction mainly used to synchronously handle asynchronous operations.
Using the following command, let’s create a new application.
# angular
ng new my-app
After creating our new application in Angular, we will go to our application directory.
# angular
cd my-app
Now, let’s run our app to check if all dependencies are installed correctly.
# angular
ng serve --open
Next, we create a promise
that will return a value after 1 second of wait time. First, we will import HttpClientModule
and add it to the imports array of AppModule
in app.module.ts
, as shown below.
# angular
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Then, we start injecting the HttpClient
inside app.component.ts
and create a constructor and define our API URL.
# angular
import { Component, VERSION, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';
constructor(private httpClient: HttpClient){}
}
Once we have injected HttpClient
, we define a fetchJson()
and call it from ngOnInit()
, so it gets initialized whenever the application is loaded. As shown below, our code in app.component.ts
will have additional code.
# angular
ngOnInit(){
this.fetchJson();
}
private fetchJson(){}
We will send a GET HTTP
request using the get()
method to return the observable. We will convert it into a promise
using toPromise()
, and we will use the then()
method.
# angular
private fetchJson(){
const promise = this.httpClient.get(this.apiUrl).toPromise();
console.log(promise);
promise.then((data)=>{
console.log("Promise resolved with: " + JSON.stringify(data));
}).catch((error)=>{
console.log("Promise rejected with " + JSON.stringify(error));
});
}
Output:
From the output above, the promise
was resolved, and it also returned the data using the then()
method that promised fetched. We can use the then()
method with a promise as a second argument.
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn