首页 文章

属性'push'在类型'Promise<any[]>'上不存在|异步

提问于
浏览
0

“属性'推''不存在于'IHero [] | Promise' . 属性'Promise'上不存在

为什么不呢?不是阵列吗?

enter image description here

在角度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

enter image description here

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 ....

enter image description here

如何让.push对此进行操作?

如果我使用传统的.then方法,那么|异步管道错误 . 出 .

enter image description here

错误之墙随之而来......

enter image description here

1 回答

  • 1
    ngOnInit() {
        this.heroes = this._heroService.getHeroes();
    }
    

    应该

    ngOnInit() {
        this._heroService.getHeroes().then(val => this.heroes = val);
    }
    

    使用您的代码,您可以分配 Promise ,它没有 push 方法 .

相关问题