简体   繁体   中英

ERROR: Property 'then' does not exist on type 'Hero[]'

app.component.ts file

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

How to resolve this error?

I got the same error; after I googled a few answers, I found that your code is no different to me and actually no error. Just need to restart the ng serve and then it compiled successfully. reference: Angular2 Tutorial: Promise error (type not assignable) in Service

Your this.heroService.getHeroes() method returns a resolved promise.

It should be

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

Instead of :

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

Try this :

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

It is working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM