Angular: Understanding ways to request API & handle the response.

In this post, we will explore the interfaces that can be used to request data from backend services and ways of handling the response in Angular (using version: “@angular/core”: “~7.0.0”).

Modern browsers support two interfaces for requesting data:

Let us explore the practical approach to use them in the angular application and ways to handle the response.

For demo purpose, I created an Avenger themed angular application. As I am early waiting for the end-game release within a span of a few days.

For mocking backend API calls, I am using Angular in-memory-web-api. It only intercepts Angular `Http` and `HttpClient`. So, won’t be able to directly hit the endpoint with curl request or using tool postman. Configuration part is easier.

npm i angular-in-memory-web-api -D

Import as a module in your app modules with your mocked in-memory service as input.

HttpClientInMemoryWebApiModule.forRoot(InMemoryAvengerService)

I created two data sets with return { avengers, powers }; will expose to end-points like:

/api/avengers 
/api/powers

Demo application: https://angular-avengers.stackblitz.io

Application is just calling these in-memory API endpoints and display data on the UI. I have created an AvengerService which will handle the calling the in-memory API and providing the response to AvengerComponent.

We are helping Fury to list down Avengers and their powers

http://geeksoncoffee.com/wp-content/uploads/2018/09/27-22.jpg

We need to list our Avengers on the page to help Fury here!! let’s take help of promises to call our Avengers.

Http Get Call

Using `Promise`: (toPromise is not a pipable operator, as it does not return an observable)

getAvengers(): Promise<Avenger[]> {
return this.http.get(this.avgUrl)
.toPromise()
.then(response => response as Avenger[])
.catch(this.handleError);
}

toPromise will return a promise response that we are handling with then/catch block and mapping response to our model class Avenger.

avengers: Avenger[] = [];this.avengerService.getAvengers()
.then(response => this.avengers = response);

Now we want to map the abilities of each Avengers with the listed specialties in the power table. Observable comes to help: Fury for the mapping powers of each Avenger.

Using `Observable`

we are creating a publisher for the HTTP get call and mapping response to our model class Power.

getPowers(): Observable<Power[]> {
return this.http.get<Power[]>(this.pwdUrl);
}
  • Component

Here, we can subscribe to the notification messages from the Observable as the data arrives and maps with the powers variable.

powers: Power[] = [];this.avengerService.getPowers()
.subscribe(response => this.powers = response);

Here you go!! Fury.

As per the theme, we can list all the movies in order that you should watch before enjoying the End-Game!!!.

fetch API

Angular doesn’t provide any wrapper for the fetch API. You can directly call it as supported by the browser. In-memory calls are only intercepted by angular HttpClient, we won’t be able to access those end-points with fetch. I hosted a JSON file as a Github gist for the demo purpose.

Service

getMovies() {
return fetch('https://gist.githubusercontent.com/akoserwal/89cded554a4289e0c7abd2625c538046/raw/219e3c207c64a96831f77f63cc72c177cf69d30c/marvel-movies.json', {
mode: "cors"
})
}

Component

marvel:any;this.avengerService.getMovies()
.then(response => {
return response.json().then(data => {
if (response.ok) {
return data;
} else {
return Promise.reject({ status: response.status, data});
}
});
})
.then(result => {
this.marvel = result;
})
.catch(error => console.log('error:', error));

With fetch API, you need to basic scaffolding for handling the response & error.

Now we can list down all the movies in the order.

Fury, How you are feeling now?

We have seen three ways to request data from backend API calls and list down response in the frontend UI

  • Promises
  • Observable
  • fetch API

You can also use async/await with above all options to based on the scenario for processing asynchronous operation on your request. Using Promises or Observable is up to your choice with Observable you will get extra advantages like you can cancel the promise. Yet depends upon the use-case.

Wait!!! we missed something

Hope you enjoyed reading this post. thank you!

References

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring