Search code examples
fetchaureliahttp-get

Not able to perform GET request by calling the fetch method on an instance of HttpClient in Aurelia


I am trying to GET request by calling the fetch method on an instance of HttpClient in Aurelia.

app.html

<template>
   <button click.delegate = "getData()">GET</button>  
</template>

app.js

import {HttpClient} from 'aurelia-fetch-client';

let client = new HttpClient();

export class App {

   getData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
 }

main.js

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-history-browser');


  aurelia.start().then(() => aurelia.setRoot());
}

I have also installed fetch bower install fetch

Now while running the application using http-server -o -c-1, I am encountering the below error

"GET /aurelia-history-browser" Error (404): "Not found"

What is that I am missing.

Update

Finally I did, but no magic (missed import 'fetch';) It's not there in the official document.

import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';

let httpClient = new HttpClient();


export class App {

    constructor() { 

    this.UserRecords = this.fetchUserDataFromWebService();

    } 

    fetchUserDataFromWebService()
    {
          var serverData = "";


         httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
              .then(response => response.json())
              .then(data => {               
                 serverData = data;             
              });

              alert('Data Received from Server');         
          return serverData;
    }
}

Only one problem: if I don't use the alert box, then I am receiving the error "Error: Value for 'UserRecords' is non-repeatable" . How to solve this?


Solution

  • answer for the question in your answer, try this:

    export class App {
    
        constructor() { 
    
        this.UserRecords = null;//.slice(0,5);
       this.fetchUserDataFromWebService();
        } 
    
        fetchUserDataFromWebService()
        {
             httpClient.fetch('http://jsonplaceholder.typicode.com/posts')
                  .then(response => response.json())
                  .then(data => {               
                     this.UserRecords = data;             
                  });
    
        }
    }