解决 Promise 时的 Angular2 错误:键入“Promise<Hero[]>"不可分配给类型 'Hero[]' [英] Angular2 Error while resolving Promise: Type &#39;Promise&lt;Hero[]&gt;&#39; is no t assignable to type &#39;Hero[]&#39;

查看:22
本文介绍了解决 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

这里是从 hero.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<Hero[]>"不可分配给类型 'Hero[]'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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