【问题标题】:Type 'Promise<Hotel[]>' is missing the following properties from type 'Hotel[]': length, pop, push, concat, and 26 more类型“Promise<Hotel[]>”缺少类型“Hotel[]”中的以下属性:length、pop、push、concat 等 26 个
【发布时间】:2022-01-02 01:48:26
【问题描述】:

this question 相关。我决定用 Promises 重写我的代码,但是如何在不需要所有 Array 属性的情况下 Promise 一个接口数组?

import { Component, OnInit } from '@angular/core';
import PouchDB from 'node_modules/pouchdb';

interface Hotel {
    name: string;
}

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
    hotels: any;
    item: Hotel[];

    constructor() {
        this.hotels = new PouchDB(<!-- db link -->, {
            auto_compaction: true
        });
    }

    ngOnInit() { this.item = this.ionViewWillEnter(); }
    ionViewWillEnter(): Promise<Hotel[]> {
        var promise = this.hotels.allDocs({
            include_docs: true
        }).then(function(result): Hotel[] {
            var data = result.rows.map(function(row): Hotel {
                return({name: row.doc.name});
            });
            return(data);
        }).catch(function(err) {
            console.log(err);
        });
        return(promise);
    }
}
Type 'Promise<Hotel[]>' is missing the following properties from type 'Hotel[]': length, pop, push, concat, and 26 more.
[ng] 23     ngOnInit() { this.item = this.ionViewWillEnter(); }

【问题讨论】:

标签: arrays angular typescript promise pouchdb


【解决方案1】:

ionViewWillEnter() 返回一个承诺,而不是一个值。所以你必须启动 promise 并使用 then() 或 await 给它一个回调。

  ngOnInit() { this.ionViewWillEnter().then(item => this.item = item); }

我建议你阅读一些关于承诺的this docs

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2019-12-28
    • 2022-01-24
    • 2019-06-25
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多