问题描述
限时送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:关键词]
发布评论