本教程关于addHero的问题(新id来自哪里)

问题描述 投票:1回答:2

当我想添加一个新的英雄时,我会使用

从heroes / heroes.component.ts添加(字符串)函数

  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
  }

来自heroes.service.ts的addHero(Hero)函数


  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }

我想知道新ID的来源。

这是现场的例子:https://stackblitz.com/angular/ombxjmbjedp

angular typescript
2个回答
0
投票

Angular用于in-memory-web-api模块,以通过RESTy API模拟CRUD操作。

此模块将自定义HttpInterceptor添加到拦截器链。在拦截器下,拦截器还负责为实体生成id。

// Create entity
// Can update an existing entity too if post409 is false.
protected post({ collection, collectionName, headers, id, req, resourceUrl, url }: RequestInfo)
   : ResponseOptions {
  const item = this.clone(this.getJsonBody(req));

  // tslint:disable-next-line:triple-equals
  if (item.id == undefined) {
    try {
      item.id = id || this.genId(collection, collectionName);

您还可以编写自己的函数来在InMemoryDataService中生成id。这正是我们在这个例子中的can see

export class InMemoryDataService implements InMemoryDbService {
 ...

// Overrides the genId method to ensure that a hero always has an id.
// If the heroes array is empty,
// the method below returns the initial number (11).
// if the heroes array is not empty, the method below returns the highest
// hero id + 1.
genId(heroes: Hero[]): number {
  return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
}

-1
投票

    addHero (hero: Hero): Observable<Hero> {
        return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
          tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
          catchError(this.handleError<Hero>('addHero'))
        );
      }

在这里你可以看到,在调用这个服务函数时我们从heroes.component.ts发送数据对象,英雄:Hero此时我们正在使用Hero作为定义的变量

addHero (hero: Hero): Observable<Hero> {
 // which is further allocated another instance 
 tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`));

所有数据都在newHero中,我们可以从中访问id。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.