Typescript 类型脚本错误类型';ArrayBuffer';不可分配给类型';项目[]和#x27;
在我的ionic项目中,我希望从postgreSql数据库的表中获取行,然后将这些行分配给项[]:currentItems 我检查postgreSql的返回行,其格式如下:Typescript 类型脚本错误类型';ArrayBuffer';不可分配给类型';项目[]和#x27;,typescript,ionic3,Typescript,Ionic3,在我的ionic项目中,我希望从postgreSql数据库的表中获取行,然后将这些行分配给项[]:currentItems 我检查postgreSql的返回行,其格式如下: [ anonymous { name: jack, email: jack@gmail.com } anonymous { name: mark, email: mark@gmail.com } ] 但是,当我将其分配给item[]:currentItems时,得到的错误如下: 类型
[
anonymous
{
name: jack,
email: jack@gmail.com
}
anonymous
{
name: mark,
email: mark@gmail.com
}
]
但是,当我将其分配给item[]:currentItems时,得到的错误如下:
类型脚本错误类型“ArrayBuffer”不能分配给类型“Item[]”。
以下是我的inoic代码的一部分:
项目1.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) => {
});;
}
项目1.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) {
}
}
谢谢看来解析JSON时可能有有效的普通对象。要解决TypeScript认为类型是
ArrayBuffer
的原因,我需要查看get
方法的声明,该方法在Items.prototype.query
方法中调用。如果您想要Item
对象而不是普通对象,则必须自己实例化它们,例如:
this.currentItems = (<any[]>resp).map((i) => new Item(i));
this.currentItems=(resp).map((i)=>newitem(i));
或者使用序列化库。要确认,如果您
console.log(resp)
,您到底看到了什么?响应可能需要某种手动转换为项[]
@MattMcCutchen,谢谢Matt。它显示:resp是:[object],[object]