0

"Property 'push' does not exist on thype 'IHero[] | Promise'. Property does not exist on type 'Promise'enter image description here

Why the heck not? isn't it an array?

enter image description here

Going through the Tour of Heroes with Angular 4 in an angular-cli project. I'm using the async pipe for the repeater instead of the official tutorial's method. 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) 
}
...

If I console.log out the this.heroes on init, I can see it is a ZoneAwarePromise....

enter image description here

How can I get the .push to work on this?

If I use a traditional .then method, then the | async pipe errors. out.

enter image description here

Wall of Errors ensues...

enter image description here

4

1 回答 1

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

应该

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

使用您的代码,您可以分配一个Promise没有push方法的代码。

于 2017-03-30T16:11:35.063 回答