2

In my ionic project, I want to get the rows from a table of a postgreSql data base, then assign the rows to a item[]: currentItems.

I check the return rows from postgreSql, it is in format as:

[
 anonymous 
 {
   name: jack,
   email: [email protected]
 }
 anonymous 
 {
   name: mark,
   email: [email protected]
 }
]

however, when I assign it to item[]: currentItems, I get the error as: Typescript Error Type 'ArrayBuffer' is not assignable to type 'Item[]'.

Below are part of my inoic code:

item.ts:

export class Item {

  constructor(fields: any) {
    // Quick and dirty extend/assign fields to this model
    for (const f in fields) {
      // @ts-ignore
      this[f] = fields[f];
    }
  }

}

list-master.ts:

export class ListMasterPage {
  currentItems: Item[];

  params: { uid: string } = {
    uid: "test"
  };

  constructor(public navCtrl: NavController,
    public items: Items,
    public modalCtrl: ModalController,
    public globalvar: GlobalvarProvider,
    public toastCtrl: ToastController) {

    this.params.uid = this.globalvar.userIdentifier
    this.items.query(this.params).subscribe((resp) => {
    /* here assign the received rows from database to the currentItems */
      this.currentItems = resp;
    }, (err) => {
    });;
  }

items.ts

export class Items {

  constructor(public api: Api) { }

  query(params?: any) {
    /* here get the rows from the postgresql database, I have confirmed the data received is in the format mentioned in above question description */
    return this.api.get('getfriends', params);
  }

  add(item: Item) {
  }

  delete(item: Item) {
  }

}

Thanks

2
  • To confirm, if you console.log(resp), what exactly do you see? The response probably needs some kind of manual conversion to an Item[]. Commented Aug 25, 2018 at 15:15
  • @MattMcCutchen, thanks Matt. it show: resp is: [object Object],[object Object] Commented Aug 26, 2018 at 1:13

1 Answer 1

1

It looks like you probably have valid plain objects from parsing JSON. To troubleshoot why TypeScript thinks the type is ArrayBuffer, I'd need to see the declaration of the get method that is called in the Items.prototype.query method. If you want Item objects instead of plain objects, you'll have to instantiate them yourself, e.g.:

this.currentItems = (<any[]>resp).map((i) => new Item(i));

or use a serialization library.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.