“属性'推''不存在于'IHero [] | Promise' . 属性'Promise'上不存在
为什么不呢?不是阵列吗?
在角度cli项目中使用Angular 4进行英雄之旅 . 我'm using the async pipe for the repeater instead of the official tutorial'的方法 . 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)
}
...
如果我在init.log上运行this.heroes,我可以看到它是一个ZoneAwarePromise ....
如何让.push对此进行操作?
如果我使用传统的.then方法,那么|异步管道错误 . 出 .
错误之墙随之而来......
1 回答
应该
使用您的代码,您可以分配
Promise
,它没有push
方法 .