我正在做有关 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/