【问题标题】:Property 'push' does not exist on type 'Promise<any[]>' with | async属性 'push' 在类型 'Promise<any[]>' 上不存在 |异步
【发布时间】: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


    【解决方案1】:
    ngOnInit() {
        this.heroes = this._heroService.getHeroes();
    }
    

    应该是

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

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

    【讨论】:

    • 对不起,我想使用异步管道。因此没有.then 的。据我了解,这就是 | async --- 所以我们可以直接将 get 调用分配给变量,而无需 .then 或 .subscribe。
    • 如果没有数组,则不能使用push()。我不知道一个好的建议。您也许可以使用从不同来源发出值的可观察对象,但这需要更多关于您的用例的知识。我什至不知道从哪里开始提问:D
    • 所以看来我必须以某种方式从 Promise 中提取数组...目标是使用 |异步管道....
    • 你想做的事情(修改收到的值)似乎与| async不兼容。
    • 正如我之前写的那样,您可以使用|async,但是您不能修改该值,或者您可以执行我在答案中发布的操作,然后您不能使用异步,并且我不明白为什么你会需要在不需要时使用| async
    猜你喜欢
    • 2019-12-31
    • 2018-10-25
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2019-12-26
    • 2017-12-25
    • 2021-02-08
    • 2019-09-20
    相关资源
    最近更新 更多