简体   繁体   English

Angular2教程:本节中的ID变量如何自动递增?

[英]Angular2 Tutorial: How is the ID variable in this section being auto incremented?

In This Section of the Angular2 Tutorial there is functionality to add new items to the array. Angular2教程的这一部分中,有一些功能可以向数组添加新项目。 When added, the ID is automatically incremented but I can't figure out what process is doing that. 添加后,ID会自动递增,但我无法确定哪个进程正在执行此操作。

I know that Arrays.push() returns the length of the array, is that length automatically inserted into the id variable in the Hero class? 我知道Arrays.push()返回数组的长度,是自动插入Hero类中的id变量的长度吗?

In hero.services.ts there is this block of code to create a hero: 在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);
}

In the heroes.component.ts there is the add 在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;
  });
}

The tutorial is using the angular 2 in-memory-web-api library. 本教程使用angular 2 in-memory-web-api库。 It is handling the post that is being made to the heroes url. 它正在处理正在对英雄网址发布的帖子。 The handler can be seen in this file on line 328: 可以在第328行的文件中看到处理程序:

https://github.com/angular/in-memory-web-api/blob/master/in-memory-backend.service.js https://github.com/angular/in-memory-web-api/blob/master/in-memory-backend.service.js

Inside that handler the id is generated via a call to the genId function whose implementation is on line 257: 在该处理程序内部,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;
};

It uses the default functionality of InMemoryDbService . 它使用InMemoryDbService的默认功能。

You can find the mock/reference in app/in-memory-dataservice.ts 您可以在app/in-memory-dataservice.ts找到mock / reference

import { InMemoryDbService } from 'angular2-in-memory-web-api

The angular source for the service can be found here: in-memory-backend.service.t (line 326) 可以在此处找到服务的角度源: in-memory-backend.service.t(第326行)

In the create method of the service, a web api gets called and posted the hero's name to it, returning a full hero object with id and name fields. 在服务的create方法中,调用web api并将英雄的名称发布到它,返回一个包含idname字段的完整英雄对象。

So I guess the incrementing and "saving" happens behind the curtains at that web api. 所以我想增量和“节约”发生在那个网络api的窗帘后面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM