簡體   English   中英

Angular2教程:本節中的ID變量如何自動遞增?

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

Angular2教程的這一部分中,有一些功能可以向數組添加新項目。 添加后,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;
};

它使用InMemoryDbService的默認功能。

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

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

可以在此處找到服務的角度源: in-memory-backend.service.t(第326行)

在服務的create方法中,調用web api並將英雄的名稱發布到它,返回一個包含idname字段的完整英雄對象。

所以我想增量和“節約”發生在那個網絡api的窗簾后面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM