Search code examples
arraysangulartypescriptpromisepouchdb

Type 'Promise<Hotel[]>' is missing the following properties from type 'Hotel[]': length, pop, push, concat, and 26 more


Related to this question. I decided to rewrite my code with Promises, but how would I Promise an Array of interfaces without requiring all of the Array properties?

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(); }

Solution

  • ionViewWillEnter() returns a promise, not a value. So you have to start the promise and give it a callback either with then() or await.

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

    I recommend you read some of this docs regarding promises.