为什么 component.ts 不能赋值给接口的变量?

Why the component.ts cannot assign to the interface's variable?

我正在尝试修改英雄之旅示例。

该服务正在从 Hero 接口返回一个名称作为可观察对象,我正在组件中订阅它。

服务

getHeroesByName(HeroName: string=''): Observable<string>
  {
       
        this.messageService.add(HeroName + "is feteched.");
        HEROES[0].name= HEROES.find(h => h.name == HeroName)?.name as string;

        return of(HEROES[0].name);
  }

组件

 export class HeroesComponent implements OnInit {
    
       //SelectedHero?= HEROES;
       Heroes: Hero[]= [];
       HeroNameReturned: Hero[]= [];
    
      selectedName= "";
      selectedHero?: Hero;
      ReturnedHero?: Hero;
    
      constructor(private heroService: HeroService) {
    
       }
    
      //  getHeroes(): void
      //  {
      //    //this.Heroes= this.heroService.getHeroes();
      //    this.heroService.getHeroes("Fazal Fasil").subscribe(heroes => this.Heroes = heroes);
      //  }
    
       getHeroesByName(selectedName: string): void
       {
         //this.Heroes= this.heroService.getHeroes();
         this.heroService.getHeroesByName(selectedName).subscribe(heroname => this.HeroNameReturned[0].name = heroname);
         this.ReturnedHero.name=  this.HeroNameReturned[0].name;
         this.Heroes.push(this.ReturnedHero);
         
         console.log(this.Heroes.length)
        
       }

但是

 this.ReturnedHero.name=  this.HeroNameReturned[0].name;

没有分配给 this.ReturnedHero.name

错误:

Object is possibly 'undefined'.ts

是因为异步。

在这里你说,ReturnedHero 可以是未定义的。

ReturnedHero?: Hero;

所以为了确保 ReturnedHero 确实有一个值,您必须将赋值放在订阅中。

getHeroesByName(selectedName: string): void {            
    this.heroService.getHeroesByName(selectedName).subscribe(
        heroname => {
            this.HeroNameReturned[0].name = heroname;
            this.ReturnedHero.name = this.HeroNameReturned[0].name;
            this.Heroes.push(this.ReturnedHero);
            console.log(this.Heroes.length);
       }
    );
}

如果你把它留在外面,赋值发生在订阅returns一个值之前很久,此时ReturnedHero仍然是未定义的。