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`

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
powers: Power[] = [];this.avengerService.getPowers()
.subscribe(response => this.powers = response);

Here you go!! Fury.

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

Fury, How you are feeling now?

  • Promises
  • Observable
  • fetch API

Wait!!! we missed something

--

--

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