hero.service.ts create()如何将id号添加到数组中(Tour of Heroes)

时间:2016-12-01 21:32:02

标签: javascript json angular rxjs

我正在做有关角度的英雄之旅教程,但我没有陷入困境我只是有一个问题。

hero.service.ts中的create()函数如何将id号添加到JSON数组中我似乎无法找到这个设置的位置,而且似乎知道如何编号列表ID号即使删除并添加!?!

hide()

有点困惑,这有助于我对这个功能的理解更好一点。

谢谢你, 布赖恩

1 个答案:

答案 0 :(得分:1)

这是Tour of Heroes应用程序用于存储Hero实体的InMemoryDataService类的礼貌。整个服务的来源可以在这里找到:

https://github.com/angular/in-memory-web-api

如果您查看post方法here,则会看到以下代码块:

if (!item.id) {
      item.id = id || this.genId(collection);
}

genId(...)的位置:

  protected genId(collection: any): any {
    // assumes numeric ids
    let maxId = 0;
    collection.reduce((prev: any, item: any) => {
      maxId = Math.max(maxId, typeof item.id === 'number' ? item.id : maxId);
    }, null);
    return maxId + 1;
  }

基本上它会创建一个新的数值,它是先前已知的最大id值的增量。