解决Promise时出现Angular2错误:输入"Promise< Hero []>"不可分配给"Hero []"类型 [英] Angular2 Error while resolving Promise: Type 'Promise<Hero[]>' is no t assignable to type 'Hero[]'

查看:58
本文介绍了解决Promise时出现Angular2错误:输入"Promise< Hero []>"不可分配给"Hero []"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新.

我正在关注Angular2教程 https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

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

这是heroes.component.ts对HeroService的调用,

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


}

用HeroService编写的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 :

错误TS2322:类型'Promise'不能分配给类型'Hero []'. 类型"Promise"中缺少属性"length".

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

请提出建议.

推荐答案

heroes: Hero[];更改为heroes: any;可解决此问题,但是控制台返回错误,因为ngFor仅支持iterables. 最后,代码会编译并运行该应用程序,但是有一个小问题困扰我.

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.

这篇关于解决Promise时出现Angular2错误:输入"Promise&lt; Hero []&gt;"不可分配给"Hero []"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆