我是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);
}
}
答案 0 :(得分:20)
将原始帖子中的演示代码转换为可替代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文件应如下所示:
<强> 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
对象。这是一个简单的模拟:
let mockUsers = [...todo: create mock user data...];
let httpMock = {
fetch: url => Promise.resolve({
json: () => mockUsers
})
};
重新配置容器以使用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$" }
]
导航到/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中查看更多说明。