使用.subscribe方法时,{{variable}}不会更新数据

时间:2018-01-08 11:45:05

标签: angular typescript

我是Angular \ TypeScript的新手。我跟着this文章,并尝试在网址中输入的英雄ID不正确或不存在时显示错误消息,无法在UI上显示,但console.log正确打印了值!我可能会在这里遗漏一些东西。

hero-detail.component.cs代码段

    public getHero() {
    this.errorMessage = '';
    this.hero = null;
    const id = +this.route.snapshot.paramMap.get('id'); 
    console.log(`[HeroDetailComponent.getHero] : id = ${id}`);
    if (isNaN(id)) {
      this.errorMessage = `Invalid Hero id!`;
      return;
    }

    this.heroService.getHero(id).subscribe(hero => this.hero = hero, error => this.handleError('getHero', error), this.getHeroComplete);
  }
  private handleError(invoker, error) {
    console.error(`[HeroDetailComponent.${invoker}] : ERROR : ${error}`);
  }
  private getHeroComplete() {
    if (this.hero == null || this.hero === undefined) {
      this.errorMessage = `None of our heroes has this id. Try next one ! :)`;
    }
    console.log(`[HeroDetailComponent.getHero] : Execution complete! ${this.errorMessage}`);
  }

hero-detail.component.html代码

<div *ngIf="hero">
    <h2>{{ hero.name | uppercase }} details</h2>
    <div><span>ID : </span> {{hero.id}} </div>
    <div><span>Name : </span> {{hero.name}} </div>
    <div>
      <label> name:
        <input [(ngModel)] = "hero.name" placeholder="name">
      </label>
    </div>
  </div>

 <button (click)="goBack()">go back</button><br>
<span style="color:red">{{errorMessage}}</span>

当执行getHero()时, console.log 会在我故意传递错误的ID时正确打印错误消息,但这并不反映在UI上。我不确定为什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可能需要在handleError方法中设置错误消息。这将在UI中显示消息。

 this.heroService.getHero(id).subscribe(hero => this.updateHero(hero), error => this.handleError('getHero', error), this.getHeroComplete);


private updateHero( hero: Hero) {
    if (hero == null || hero === undefined) {
       this.errorMessage = `None of our heroes has this id. Try next one ! :)`;
    }
    this.hero = hero;
}

 private handleError(invoker, error) {
    console.error(`[HeroDetailComponent.${invoker}] : ERROR : ${error}`);
    this.errorMessage  = "ERROR : ${error}`";
  }