i'm brand new aurelia.
how change following code provide dummy httpclient, e.g. json reader instead provide static set of json data, negating need server in development.
import {inject} 'aurelia-framework'; import {httpclient} '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); } }
there's couple steps required demo code in original post state can substitute httpclient implementations.
step 1
remove configuration code in class's constructor...
these lines:
users.js
... http.configure(config => { config .usestandardconfiguration() .withbaseurl('https://api.github.com/'); }); ...
should move main.js
file:
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); // <---- line ensures `@inject`s `httpclient` instance instance configured above. }
now our users.js file should this:
users.js
import {inject} 'aurelia-framework'; import {httpclient} '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); } }
step 2:
mock httpclient.
the user.js module uses fetch
method returns response
object has json
method. here's simple mock:
let mockusers = [...todo: create mock user data...]; let httpmock = { fetch: url => promise.resolve({ json: () => mockusers }) };
step 3:
reconfigure container use http mock:
in step 1 added configurecontainer
function main.js
module registered configured httpclient instance in container. if wanted use our mock version configurecontainer
function change this:
main.js
... let mockusers = [...todo: create mock user data...]; let httpmock = { fetch: url => promise.resolve({ json: () => mockusers }) }; function configurecontainer(container) { container.registerinstance(httpclient, httpmock); }
more info on configuring container here: https://github.com/aurelia/dependency-injection/issues/73
Comments
Post a Comment