【问题标题】:Why the component.ts cannot assign to the interface's variable?为什么 component.ts 不能分配给接口的变量?
【发布时间】:2021-08-13 02:34:35
【问题描述】:

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

该服务从 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

【问题讨论】:

    标签: angular typescript angular8 single-page-application


    【解决方案1】:

    这是因为异步。

    这里你说,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);
           }
        );
    }
    

    如果您将其留在外面,则赋值发生在订阅返回值之前很久,此时ReturnedHero 仍未定义。

    【讨论】:

    • 您好,谢谢。但同样的错误:对象可能是 'undefined'.ts(2532)
    • 哦,现在我明白了。你的问题是,你根本没有英雄对象。它是并且将保持未定义。因此,您不能在 name-property 中放置一些东西。所以你必须想办法让ReturnedHero在之前成为一个有效的英雄对象,或者让getHeroesByName()返回一个英雄对象列表而不仅仅是英雄名称列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多