首页 > 解决方案 > 是否可以将多个 ID 传递给 angular-in-memory-web-api 中的查询字符串?

问题描述

例如,我想做这样的事情:

{hostURL}/api/entities/14/15/16/17

这反过来又会带回相应 ID 的所有数据。这种方法行不通。我也试过这个,它也不起作用:

{hostURL}/api/entities?id=16&id=17

文档展示了如何使用一个 ID(在 HTTP 请求处理下):https ://github.com/angular/in-memory-web-api

有没有办法传入多个ID?

谢谢。

标签: angularangular-in-memory-web-api

解决方案


绕过它。我在 angular-in-memory-web-api 文档中找到了这个 GitHub 文件:https ://github.com/angular/in-memory-web-api/blob/master/src/app/hero-in-mem- data-override.service.ts并构建了以下解决方案:

import { getStatusText, STATUS } from 'angular-in-memory-web-api/http-status-codes';
import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';

  get(reqInfo: RequestInfo) {
    // Extract ids from URL
    const ids: Array<number> = reqInfo.req.urlWithParams.match(/[0-9]+/g).map(n => +(n));
    // If there's more than one ID in the URL then we call the appropriate function
    if (ids.length > 1) {
      return this.getRelationshipDetails(reqInfo, ids)
    }
  }

private getRelationshipDetails(reqInfo: RequestInfo, ids: Array<number>) {
  console.log('HTTP GET override')
  const entities = reqInfo.collection;
  return reqInfo.utils.createResponse$(() => {
    const data = entities.filter(entity => ids.indexOf(entity.id) !== -1)
    const dataEncapsulation = reqInfo.utils.getConfig().dataEncapsulation;
    const options: any = data ?
      {
        body: dataEncapsulation ? { data } : data,
        status: STATUS.OK
      } :
      {
        body: { error: `Entities with ids='${ids}' not found` },
        status: STATUS.NOT_FOUND
      };
    return this.finishOptions(options, reqInfo)
  });
}

private finishOptions(options: any, { headers, url }: RequestInfo) {
  options.statusText = getStatusText(options.status);
  options.headers = headers;
  options.url = url;
  return options;
}

推荐阅读