Angular-in-memory-web-api中的多个集合

Spa*_*row 37 api in-memory-database angular

我们如何使用Angular-in-memory-web-api创建多个集合?单个集合不是问题.但是我无法为多个集合实现它.

例如,我想在内存db - Country和Cities中创建两个集合.任何想法,怎么做?

Pau*_*tha 61

只需返回一个包含两个数组的对象.在Angular的例子中,你会看到类似的东西

createDb() {
  let heroes = [ .. ]
  return { heroes }
}
Run Code Online (Sandbox Code Playgroud)

如果您还不知道这一点,那{ heroes }只是写作的简写{ heroes: heroes }.因此,如果您有两个集合,那么只需将其添加为另一个属性即可

createDb() {
  let heroes = [ .. ];
  let crises = [ .. ];
  return { heroes, crises };
  // or { heroes: heroes, crises: crises }
}
Run Code Online (Sandbox Code Playgroud)

返回的属性名称将用于URL中的路径.所以你可以使用

/api/heroes/1
/api/crises/1
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 13

保罗答案中 描述的方法是正确的,但是我想错过一个我想补充的细节:你如何genId正确指定,所以它适用于两个集合?

答案是指用TypeScript(JavaScript的超集)编写的"Heroes"示例,特别是HTTP章节.在那里,heroes通过实现模拟表:

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11, name: 'Mr. Nice' },
      { id: 12, name: 'Narco' },
      // ...
      { id: 20, name: 'Tornado' }
    ];
    return {heroes};
  }

  // Overrides the genId method to ensure that a hero always has an id.
  // If the heroes array is empty,
  // the method below returns the initial number (11).
  // if the heroes array is not empty, the method below returns the highest
  // hero id + 1.
  genId(heroes: Hero[]): number {
    return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您添加第二个集合crises,如他的答案中所示,即:

createDb() {
  let heroes = [ { ... }, ... ];
  let crises = [ { ... }, ... ];
  return { heroes, crises };
  // or { heroes: heroes, crises: crises }
}
Run Code Online (Sandbox Code Playgroud)

你如何提供genId两个集合(只要它们是类型HeroCrises)?如你所做的那样重载C#在TypeScript 中不起作用,它会抛出一个错误("Duplicate function implementation").


解决方案: 我发现,您可以使用TypeScript的Generics解决此问题,如下所示.用genId以下通用版本替换otiginal 函数:

genId<T extends Hero | Crises>(myTable: T[]): number {
  return myTable.length > 0 ? Math.max(...myTable.map(t => t.id)) + 1 : 11;
}
Run Code Online (Sandbox Code Playgroud)

这里重要的是部分<T extends Hero | Crises>:它意味着类型T可以是HeroCrises:所以如果传递的参数是类型Hero[]或者,它将被调用Crises[].

有了这些知识,添加第3,第4 ......类很简单:只需附加类.假设我们要添加类SuperHero,那么您只需将其附加到| SuperHero,所以它看起来像:

genId<T extends Hero | Crises | SuperHero>(myTable: T[]): number {
  return myTable.length > 0 ? Math.max(...myTable.map(t => t.id)) + 1 : 11;
}
Run Code Online (Sandbox Code Playgroud)

注:作为先决条件,所有类(Hero,CrisesSuperHero)需要有一个数字id财产申报.


有用的链接:

  • @Matt,很高兴您提供了文档/相关文章的链接 (2认同)