【问题标题】:Angular 6 tour of heroes tutorial - how to add more properties in HTTP post Observable functionAngular 6英雄之旅教程-如何在HTTP post Observable函数中添加更多属性
【发布时间】:2018-05-26 14:59:32
【问题描述】:

我在 Hero 模型的 id 和 name 旁边添加了 description 属性 hero.ts:

export class Hero{
 id: number;
 name: string;
 description: string;
}

现在在教程的 HTTP 部分,我正在尝试使用他们在教程中提供的功能添加一个新英雄:

src/app/heroes/heroes.component.html(添加):

<div>
  <label>Hero name:
    <input #heroName />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="add(heroName.value); heroName.value=''">
    add
  </button>
</div>

src/app/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);
    });
}

src/app/hero.service.ts (addHero):

/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions);
}
enter code here

我应该在哪个功能中添加什么才能推送英雄描述?

【问题讨论】:

    标签: angular


    【解决方案1】:

    在 HTML 中添加输入字段并在单击按钮后扩展操作

    src/app/heroes/heroes.component.html:

    <div>
      <label>Hero name:
        <input #heroName />
      </label>
      <label>Hero description:
        <input #heroDescription />
      </label>
      <!-- (click) passes input value to add() and then clears the input -->
      <button (click)="add(heroName.value, heroDescription .value); heroName.value=''; heroDescription.value =''">
        add
      </button>
    </div>
    

    调整 add() 函数,使其将描述作为参数并将其添加到 hero 对象中。根据描述是否可选,您可以更改 if 语句。

    src/app/heroes/heroes.component.ts:

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

    【讨论】:

      【解决方案2】:

      一种选择是实例化一个英雄:

      private _hero :Hero=new Hero();
      

      并绑定它:

      <div>
          <label>Hero name:
            <input [(ngModel)]="_hero.name" />
          </label>
          <label>Hero description:
            <input [(ngModel)]="_hero.description"/>
          </label>
          <!-- (click) passes input value to add() and then clears the input -->
          <button (click)="add()">
            add
          </button>
        </div>
      

      并且在添加中你可以发送一个英雄:这里控制台日志进行演示

      add(): void {
          console.log(this._hero.name  + this._hero.description);
          }
      

      【讨论】:

        猜你喜欢
        • 2017-03-26
        • 1970-01-01
        • 2019-02-14
        • 2017-04-22
        • 1970-01-01
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多