The lightbringer The lightbringer - 4 months ago 166
JSON Question

Aurelia typescript load json service

I am trying to create a class that will have two functions:
1) Load items from a json stored in my local server and return that variable with all the items.
2) Return a single item by id.
The problem is I want to use these two methods from different modules, and I do not know how to go about implementing the module and using it. So far, I have been able to implement the http part with aurelia's fetch client, but I don't know how to make the function:

function getItems() {
// some http request code
return fetchedItems;
}


Because the code in aurelia.io does something like this (which I have tried and actually works if I print the data):

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

export function getItems(url) {
let client = new HttpClient();
client.configure(config => {
config
.withBaseUrl('api/')
.withDefaults({
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'Fetch'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
});
});

client.fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
});
}


All this works ok. The point is that instead of doing 'console.log(data);' I want to return it, but so far the only thing that seems to work is assigning the returned items to a local class variable with 'this.items = data'. I would be ok with this so long as I get a function that allows to do this:

let items = getItems();


And

let item = getItemById(id);


EDIT: SOLVED

Users should note that, in order for this to work, they should have this in their tsconfig.js:

"target": "es6"


Because async/await requires at least ES2015.

Answer

Use async / await

If you're using TypeScript and targeting ES6, you can use the await/async keywords.

export async function getItems(url) {
    let client = new HttpClient();
    client.configure(config => {
      config
        .withBaseUrl('api/')
        .withDefaults({
          credentials: 'same-origin',
          headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'Fetch'
          }
        })
        .withInterceptor({
          request(request) {
            console.log(`Requesting ${request.method} ${request.url}`);
            return request;
          },
          response(response) {
            console.log(`Received ${response.status} ${response.url}`);
            return response;
          }
        });
    });

    return await client.fetch(url)
      .then(response => response.json());

}