数组 – Angular2教程:本节中的ID变量如何自动递增?
发布时间:2020-12-17 17:54:24 所属栏目:安全 来源:网络整理
导读:在 This Section of the Angular2 Tutorial中,可以向阵列添加新项目.添加后,ID会自动递增,但我无法确定哪个进程正在执行此操作. 我知道Arrays.push()返回数组的长度,是自动插入Hero类中的id变量的长度吗? 在hero.services.ts中有一段代码来创建一个英雄: c
在
This Section of the Angular2 Tutorial中,可以向阵列添加新项目.添加后,ID会自动递增,但我无法确定哪个进程正在执行此操作.
我知道Arrays.push()返回数组的长度,是自动插入Hero类中的id变量的长度吗? 在hero.services.ts中有一段代码来创建一个英雄: 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); } 在heroes.component.ts中有添加 add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.create(name) .then(hero => { this.heroes.push(hero); this.selectedHero = null; }); } 解决方法
本教程使用的是
angular 2 in-memory-web-api库.它正在处理正在对英雄网址发布的帖子.可以在第328行的文件中看到处理程序:
https://github.com/angular/in-memory-web-api/blob/master/in-memory-backend.service.js 在该处理程序内部,id通过调用genId函数生成,该函数的实现位于第257行: InMemoryBackendService.prototype.genId = function (collection) { // assumes numeric ids var maxId = 0; collection.reduce(function (prev,item) { maxId = Math.max(maxId,typeof item.id === 'number' ? item.id : maxId); },null); return maxId + 1; }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |