解决 Promise 时的 Angular2 错误:键入“Promise<Hero[]>"不可分配给类型 'Hero[]'

编程入门 行业动态 更新时间:2024-10-28 12:16:37
本文介绍了解决 Promise 时的 Angular2 错误:键入“Promise<Hero[]>"不可分配给类型 'Hero[]'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

已更新.

我正在关注 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

这里是从 heroponent.ts 调用 HeroService,

Here is the call to HeroService from heroesponent.ts,

Heroesponent.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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 09:55:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1000533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不可分   错误   类型   lt   Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!