Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. When added, the ID is automatically incremented but I can't figure out what process is doing that.

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

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

In the heroes.component.ts there is the add

add(name: string): void {
  name = name.trim();
  if (!name) { return; }
  this.heroService.create(name)
    .then(hero => {
    this.heroes.push(hero);
    this.selectedHero = null;
  });
}
like image 369
Decius Avatar asked Jan 05 '23 09:01

Decius


2 Answers

The tutorial is using the angular 2 in-memory-web-api library. It is handling the post that is being made to the heroes url. The handler can be seen in this file on line 328:

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:

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;
};
like image 186
Rick Avatar answered Jan 13 '23 10:01

Rick


It uses the default functionality of InMemoryDbService .

You can find the mock/reference in app/in-memory-dataservice.ts

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)

like image 27
Nix Avatar answered Jan 13 '23 08:01

Nix