【问题标题】:ERROR: Property 'then' does not exist on type 'Hero[]'错误:“Hero []”类型上不存在属性“then”
【发布时间】:2017-05-10 07:49:28
【问题描述】:

app.component.ts 文件

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [HeroService]
})

export class AppComponent implements OnInit{
  title = 'Tour of Heroes';
  heroes : Hero[ ];
  selectedHero : Hero;
  constructor(private heroService: HeroService) { }
      getHeroes(): void {
     this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  };
    ngOnInit(): void {
    this.getHeroes();
  };
    onSelect(hero: Hero): void{
    this.selectedHero = hero;
  };
}

hero.service.ts

import { Injectable } from '@angular/core'; 
import { Hero } from './hero'; 
import { HEROES } from './mock-heroes'; 

@Injectable() 
export class HeroService { 

    getHeroes(): Promise<Hero[]> { 
        return Promise.resolve(HEROES); 
    } 
}

如何解决这个错误?

【问题讨论】:

  • 你能在你的服务中显示getHeroes方法吗?
  • 猜你返回的是Hero[],应该是Promise&lt;Hero[]&gt;,而不是heroService.getHeroes()
  • hero.service.ts 文件导入 { Injectable } from '@angular/core';从'./hero'导入{英雄};从'./mock-heroes'导入{英雄}; @Injectable() 导出类 HeroService { getHeroes(): Promise { return Promise.resolve(HEROES); } }
  • 您应该使用该代码编辑您的初始问题

标签: angularjs angular typescript


【解决方案1】:

我遇到了同样的错误;在我搜索了几个答案后,我发现您的代码与我没有什么不同,实际上也没有错误。只需要重新启动 ng serve 即可编译成功。 参考:Angular2 Tutorial: Promise error (type not assignable) in Service

【讨论】:

  • 这里也是,编辑 hero.service.ts 并保存,然后就可以了。
  • 这应该被标记为正确答案。我用 'ng serve' 重新编译,它工作了
  • 关于为什么 ng serve 需要重新启动的任何解释?
【解决方案2】:

您的 this.heroService.getHeroes() 方法返回一个已解决的承诺。

应该是

this.heroes = this.heroService.getHeroes();

【讨论】:

  • this.heroService.getHeroes().then((heroes =&gt; this.heroes = heroes); 取决于视图中是否使用了 |async
【解决方案3】:

代替

getHeroes(): Promise<Hero[]> { 
  return Promise.resolve(HEROES); 
} 

试试这个

getHeroes(): Promise<Hero[]> {
  return new Promise(resolve => {
  resolve(HEROES);
 });
}

它正在工作

【讨论】:

    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 2021-05-31
    • 2020-01-11
    • 2020-12-27
    相关资源
    最近更新 更多