错误:'Hero []'

时间:2017-05-10 07:49:28

标签: angularjs angular typescript

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); 
    } 
}

如何解决此错误?

3 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:5)

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

应该是

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

答案 2 :(得分:2)

而不是

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

试试这个

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

它正在运作