Aurelia-fetch-client is a forward-looking HttpClient based on the Fetch API specification.It supports all HTTP verbs and integrates with Service Workers, including Request/Response caching. In this article, we will look into how to use Aurelia-fetch-client for a HTTP GET Request.
Introduction
Aurelia-fetch-client is a forward-looking HttpClient based on the Fetch API specification.It supports all HTTP verbs and integrates with Service Workers, including Request/Response caching. In this article, we will look into how to use Aurelia-fetch-client for a HTTP GET Request.
Aurelia - Project Setup
Create a folder say AureliaExperiment at your favorite location.
Then download the basic Aurelia project setup zipped file from here.
Extract the Zipped file and copy it under AureliaExperiment folder. It looks as under
Straight to Experiment
At first, we need to import two statements.
import 'fetch';
import {HttpClient} from 'aurelia-fetch-client';
Then invoke the fetch method on the httpClient instance as shown below in the app.js file.
app.js
---------
import 'fetch';
import {HttpClient} from 'aurelia-fetch-client';
let httpClient = new HttpClient();
export class App {
constructor() {
this.UserRecords = null;
this.fetchUserDataFromWebService();
}
fetchUserDataFromWebService()
{
httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
this.UserRecords = data;
});
}
}
By default, fetch makes GET requests. All calls to fetch return a Promise object which is used for asynchronous computations. This Promise object will resolve to a Response object. Using this Response object, we parse content and assign it to the UserRecords property.
Now let's open the app.html file and write the below template
app.html
---------
<template>
<table border="1">
<thead>
<tr>
<td><b>Id</b></td>
<td><b>UserId</b></td>
<td><b>Title</b></td>
<td><b>Description</b></td>
</tr>
</thead>
<tbody>
<tr repeat.for="userRecord of UserRecords">
<td>${userRecord.id}</td>
<td>${userRecord.userId}</td>
<td>${userRecord.title}</td>
<td>${userRecord.body}</td>
</tr>
</tbody>
</table>
</template>
The purpose of Repeat.for is to iterate over objects. After we iterate the UserRecords array, we have bound the properties of the object by using the {object.property} syntax of Aurelia. The result is as under
Reference
aurelia-fetch-client
Conclusion
In this article we have learnt how to use Aurelia-fetch-client for a HTTP GET Request. Hope this will be useful. Thanks for reading. Zipped file attached.