Aurelia打字稿加载json服务

时间:2016-07-19 15:54:41

标签: json aurelia aurelia-fetch-client

我正在尝试创建一个具有两个函数的类: 1)从存储在本地服务器中的json加载项目,并返回包含所有项目的变量。 2)按ID返回单个项目。 问题是我想从不同的模块中使用这两种方法,我不知道如何实现模块并使用它。到目前为止,我已经能够使用aurelia的fetch客户端实现http部分,但我不知道如何使用该函数:

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

因为aurelia.io中的代码做了类似这样的事情(我已经尝试过并且在打印数据时实际工作):

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

这一切都运转正常。关键是不要做'console.log(data);'我想返回它,但到目前为止,唯一似乎有用的是将返回的项目分配给带有'this.items = data'的本地类变量。只要我得到一个允许这样做的功能,我就会对此感到满意:

let items = getItems();

let item = getItemById(id);

编辑:已解决

用户应注意,为了使其正常工作,他们应该在tsconfig.js中使用它:

"target": "es6"

因为async / await至少需要ES2015。

2 个答案:

答案 0 :(得分:2)

使用async / await

如果您使用的是TypeScript并定位ES6,则可以使用await / async个关键字。

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

}

答案 1 :(得分:0)

client.fetch会返回一个承诺,所以你只需要返回它:

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

使用该功能:

getItems(url)
  .then(data => this.someProperty = data);