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

npm i angular-in-memory-web-api -D
HttpClientInMemoryWebApiModule.forRoot(InMemoryAvengerService)
/api/avengers 
/api/powers

We are helping Fury to list down Avengers and their powers

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

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);
}
avengers: Avenger[] = [];this.avengerService.getAvengers()
.then(response => this.avengers = response);

Using `Observable`

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

Here you go!! Fury.

fetch API

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));

Fury, How you are feeling now?

  • Promises
  • Observable
  • fetch API

Wait!!! we missed something

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring https://mentorcruise.com/mentor/abhishekkoserwal/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How Does Javascript work?

Javascript Mechanism

Spheres — the tutorial

Leetcode Q406. Queue Reconstruction by Height (Q346)

Create Your First App in React Native with Expo

Achieve the 3D depth by canvas 2D abilities

Creating Custom React Hooks

Creating Custom React Hooks

https://medium.com/@shciyj2010/list/predefined:15bcb457eaba:READING_LIST

If You Use TailwindCSS, Here Are The Best Resources That You Can Bookmark

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhishek koserwal

Abhishek koserwal

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring https://mentorcruise.com/mentor/abhishekkoserwal/

More from Medium

Application Structure and Best Practices Of Angular — Part 2

RxJs asyncScheduler: async dropdown options data

Design System Fonts in Angular

Azure AD with Angular and Express.js