typescript 错误:“Hero[]”类型上不存在属性“then”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43886460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ERROR: Property 'then' does not exist on type 'Hero[]'
提问by Om Patel
app.component.ts file
app.component.ts 文件
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [HeroService]
})
export class AppComponent 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();
};
onSelect(hero: Hero): void{
this.selectedHero = hero;
};
}
hero.service.ts
英雄服务.ts
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
}
How to resolve this error?
如何解决这个错误?
采纳答案by eko
Your this.heroService.getHeroes()
method returns a resolved promise.
您的this.heroService.getHeroes()
方法返回一个已解决的承诺。
It should be
它应该是
this.heroes = this.heroService.getHeroes();
回答by early
I got the same error; after I googled a few answers, I found that your code is no different to me and actually no error. Just need to restart the ng serve and then it compiled successfully. reference: Angular2 Tutorial: Promise error (type not assignable) in Service
我遇到了同样的错误;在我用谷歌搜索了几个答案后,我发现你的代码对我来说没有什么不同,实际上没有错误。只需要重启 ng serve 就可以编译成功了。参考:Angular2 教程:服务中的 Promise 错误(类型不可分配)
回答by usefulBee
Instead of:
而不是:
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
Try this:
试试这个:
getHeroes(): Promise<Hero[]> {
return new Promise(resolve => {
resolve(HEROES);
});
}
It is working
这是工作