你如何替代Aurelia的HttpClient?

时间:2016-02-01 21:30:49

标签: javascript json aurelia

我是Aurelia的新手。

如何更改以下代码以提供虚拟HttpClient,例如相反,json读取器只提供一组静态的json数据,无需开发中的服务器。

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

@inject(HttpClient)
export class Users {
  heading = 'Github Users';
  users = [];

  constructor(http) {
    http.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl('https://api.github.com/');
    });

    this.http = http;
  }

  activate() {
    return this.http.fetch('users')
      .then(response => response.json())
      .then(users => this.users = users);
  }
}

2 个答案:

答案 0 :(得分:20)

将原始帖子中的演示代码转换为可替代HttpClient实现的状态需要几个步骤。

第1步

删除类的构造函数中的配置代码......

这些行:

<强> users.js

...
http.configure(config => {
  config
    .useStandardConfiguration()
    .withBaseUrl('https://api.github.com/');
});
...

应移至main.js文件:

<强> main.js

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging();

  configureContainer(aurelia.container);  // <--------

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

function configureContainer(container) {
  let http = new HttpClient();
  http.configure(config => {
    config
      .useStandardConfiguration()
      .withBaseUrl('https://api.github.com/');
  });
  container.registerInstance(HttpClient, http); // <---- this line ensures everyone that `@inject`s a `HttpClient` instance will get the instance we configured above.
}

现在我们的users.js文件应如下所示:

<强> users.js

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

@inject(HttpClient)
export class Users {
  heading = 'Github Users';
  users = [];

  constructor(http) {
    this.http = http;
  }

  activate() {
    return this.http.fetch('users')
      .then(response => response.json())
      .then(users => this.users = users);
  }
}

第2步:

模拟HttpClient。

user.js模块仅使用fetch方法,该方法返回具有Response方法的json对象。这是一个简单的模拟:

let mockUsers = [...todo: create mock user data...];

let httpMock = {
  fetch: url => Promise.resolve({
    json: () => mockUsers
  })
};

第3步:

重新配置容器以使用http mock:

在第1步中,我们向configureContainer模块添加了main.js函数,该模块在容器中注册了已配置的HttpClient实例。如果我们想使用我们的模拟版本,configureContainer函数将更改为:

<强> main.js

...

let mockUsers = [...todo: create mock user data...];

let httpMock = {
  fetch: url => Promise.resolve({
    json: () => mockUsers
  })
};

function configureContainer(container) {      
  container.registerInstance(HttpClient, httpMock);
}

有关在此配置容器的更多信息:https://github.com/aurelia/dependency-injection/issues/73

答案 1 :(得分:2)

还有另一种可能性,即在开发过程中为应用程序提供静态数据。 Navigation Skeleton已经附带了Gulp和BrowserSync,因此我们使用它来伪造API调用。

假设您从/api虚拟目录加载JSON数据,例如

GET /api/products

在这种情况下,你只需要两件事来伪造它。

将模拟数据放入文件

转到Aurelia应用的根文件夹,创建一个/api文件夹。

创建一个/api/products子文件夹并放入一个名为GET.json的新文件。该文件应包含JSON,例如

<强> GET.json

[ { "id": 1, "name": "Keyboard", "price": "60$" },
  { "id": 2, "name": "Mouse", "price": "20$" },
  { "id": 3, "name": "Headphones", "price": "80$" }
]

配置BrowserSync以模拟API调用

导航到/build/tasks文件夹并编辑serve.js文件。将serve task的定义更改为以下代码:

gulp.task('serve', ['build'], function(done) {
  browserSync({
    online: false,
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      middleware: function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');

        // Mock API calls
        if (req.url.indexOf('/api/') > -1) {
          console.log('[serve] responding ' + req.method + ' ' + req.originalUrl);

          var jsonResponseUri = req._parsedUrl.pathname + '/' + req.method + '.json';

          // Require file for logging purpose, if not found require will 
          // throw an exception and middleware will cancel the retrieve action
          var jsonResponse = require('../..' + jsonResponseUri);

          // Replace the original call with retrieving json file as reply
          req.url = jsonResponseUri;
          req.method = 'GET';
        }

        next();
      }
    }
  }, done);
});

现在,当您运行gulp serve时,BrowserSync将处理您的API调用并从磁盘上的静态文件提供它们。

您可以在我的github repo中查看示例,并在Mocking API calls in Aurelia中查看更多说明。