web-dev-qa-db-fra.com

ERREUR: la propriété 'then' n'existe pas sur le type 'Hero []'

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

Comment résoudre cette erreur?

10
Om Patel

Votre méthode this.heroService.getHeroes() renvoie une promesse résolue.

CA devrait etre

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

Au lieu de

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

Essaye ça :

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

Ça fonctionne

2
usefulBee