【发布时间】:2017-08-24 16:28:31
【问题描述】:
“类型'IHero [] | Promise'上不存在属性'push'。类型'Promise'上不存在属性
为什么不呢?不是数组吗?
在 angular-cli 项目中使用 Angular 4 完成英雄之旅。我正在使用异步管道作为中继器,而不是官方教程的方法。 https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
heroes.component.ts
export class HeroesComponent implements OnInit {
heroes: IHero[]|Promise<IHero[]> = [];
selectedHero: IHero;
constructor(private _heroService: HeroService, private _router: Router)
ngOnInit() {
this.heroes = this._heroService.getHeroes();
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
this._heroService.create(name)
.then(hero => {
this.heroes.push(hero); // RED SQUIGGLY ERROR HERE "Property 'push' does not exist on thype 'IHero[] | Promise<IHero[]>'. Property does not exist on type 'Promise<IHero[]>'"
});
}
}
hero.service.ts
...
getHeroes(): Promise<IHero[]> {
return this._http.get(this.heroesUrl)
.toPromise()
.then( res => res.json().data as IHero[] )
.catch( this._handleError)
}
...
如果我 console.log out this.heroes on init,我可以看到它是一个 ZoneAwarePromise....
我怎样才能让 .push 来解决这个问题?
如果我使用传统的 .then 方法,那么 |异步管道错误。出去。
错误之墙随之而来......
【问题讨论】:
标签: angular asynchronous typescript promise angular4