Angular2 Error while resolving Promise: Type 'Promise<Hero[]>' is no t assignable to type 'Hero[]'
Asked Answered
P

1

1

Updated.

I am Following Angular2 tutorial from https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

Here is the call to HeroService from heroes.component.ts,

Heroes.component.ts

import { Component , OnInit } from '@angular/core';

import { Hero } from './hero';

import { HeroService } from './hero.service';



@Component({
  selector: 'my-heroes',
  template: `


        <h2>My Heroes</h2>
        <ul class="heroes">
            <li *ngFor="let hero of heroes">
                 <span class="badge">{{hero.id}}</span> {{hero.name}}
            </li>
         </ul> `,

})

export class HeroesComponent 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();
    }


}

And getHeroes() call written in HeroService

HeroService.ts

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

@Injectable()
export class HeroService{
    getHeroes() { 
       return Promise.resolve(HEROES);
     }
}

I get the following compile time error :

error TS2322: Type 'Promise' is not assignable to type 'Hero[]'. Property 'length' is missing in type 'Promise'.

Please suggest.

Prorate answered 26/5, 2017 at 13:27 Comment(4)
Can you show the full Component code for where you have those 2 functions please? You can exclude anything that is not mentioned in those code blocks of yourJustle
at that page of the tutorial, you should import in the hero service the mock-heroes. Did you import it correctly? import { HEROES } from './mock-heroes'; And of course defining the file moch-heroes witht he list of heroesGaff
Can you provide the full Error line? It should mention a file and line number. I have a suspicion, but the line number will make sure. Tell us which line in your question the line number refers to in the errorJustle
I had a similar error in the tutorial. Restarting the server fixed my problem. See #44217033Costermonger
I
1

Changing heroes: Hero[]; to heroes: any; resolves the issue, however the console returns an error because ngFor supports only iterables. At the end, the code compile and the app runs but there's this tiny issue that I find disrupting.

Insolate answered 28/8, 2017 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.