javascript - Hero.service.ts create() 如何将id号添加到数组中(英雄之旅)

标签 javascript json angular rxjs

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

hero.service.ts 中的 create() 函数如何将 id 编号添加到 JSON 数组中我似乎找不到它的设置位置,而且该东西似乎知道如何对列表 id 编号进行编号删除并添加!?!

    create(name: string): Promise<Hero> {
     return this.http
       .post(this.heroesUrl, JSON.stringify({name: name}), {headers:   this.headers})
       .toPromise()
       .then(res => res.json().data)
       .catch(this.handleError)
    }

只是有点困惑,这将有助于我更好地理解这个函数。

谢谢你, 布莱恩

最佳答案

这是英雄之旅应用程序用于存储英雄实体的 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 值的增量。

关于javascript - Hero.service.ts create() 如何将id号添加到数组中(英雄之旅),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920776/

相关文章:

javascript - 如何使此 slider 在单击下一个和上一个时显示 2 个引号

c# - 如何从 javascript 调用 WCF 服务?

python - 通过curl/urllib2向Pyramid应用程序发送json数据没有给出正确的请求。POST

javascript - JSON.parse 无法从字符串创建对象

javascript - 如果单击子angular2,如何停止父请求

angular - 选择日期和时间后,p-calendar 弹出模式不会关闭

javascript - 子字符串不适用于 childNodes[0].nodeValue

javascript - 我想通过单击 ID 为 ="add_city"的按钮来激活该功能,到目前为止,按下 Enter 时会激活该功能

python - 在python中从JSON中检索数据,如果对象名称匹配,则存储该对象的 key

Angular 6 MatDialog取消关闭事件