我是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); } }
要使原始文章中的演示代码达到可以替代HttpClient实现的状态,需要执行几个步骤。
在类的构造函数中删除配置代码…
这些行:
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文件应如下所示:
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); } }
模拟HttpClient。
user.js模块仅使用fetch方法,该方法返回Response具有json方法的对象。这是一个简单的模拟:
fetch
Response
json
let mockUsers = [...todo: create mock user data...]; let httpMock = { fetch: url => Promise.resolve({ json: () => mockUsers }) };
重新配置容器以使用http模拟:
在第1步中,我们向模块中添加了一个configureContainer函数,该函数main.js在容器中注册了已配置的HttpClient实例。如果我们想使用模拟版本,该configureContainer函数将更改为:
configureContainer
... 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