Angular2 Study Guide. How does the ID variable in this section automatically increase?

In This section of Angular2 Tutorial has the function of adding new elements to an array. When adding, the identifier automatically increases, but I can not understand which process does this.

I know that Arrays.push () returns the length of the array, is this length automatically inserted into the id variable in the Hero class?

Hero.services.ts has this code block for creating a hero:

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);
}

There is an addition in the heroes.component.ts file

add(name: string): void {
  name = name.trim();
  if (!name) { return; }
  this.heroService.create(name)
    .then(hero => {
    this.heroes.push(hero);
    this.selectedHero = null;
  });
}
+4
source share
3 answers

angular 2 in-memory-web-api . , URL- . 328:

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

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;
};
+7

InMemoryDbService.

mock/reference app/in-memory-dataservice.ts

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

angular : in-memory-backend.service.t( 326)

+2

create -api , - id name.

, , "" -.

0

Source: https://habr.com/ru/post/1654571/


All Articles