你如何替换 Aurelia 中的 HttpClient?

How do you substitute HttpClient in Aurelia?

我是 Aurelia 的新手。

您将如何更改以下代码以提供虚拟 HttpClient,例如json reader 相反,它只会提供一组静态的 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);
  }
}

需要几个步骤才能使原始 post 中的演示代码达到我们可以替换 HttpClient 实现的状态。

步骤 1

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

这些行:

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 方法,其中 returns 具有 json 方法的 Response 对象。这是一个简单的模拟:

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

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

第 3 步:

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

在第 1 步中,我们向 main.js 模块添加了一个 configureContainer 函数,用于在容器中注册已配置的 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

还有一种可能是在开发期间为应用程序提供静态数据。 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 文件。将服务任务的定义更改为以下代码:

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 and more description in my Mocking API calls in Aurelia中看到一个例子。