如何修复'Item'缺少类型'Item []'中的以下属性:length,pop,push,concat和另外26个

时间:2019-04-21 20:09:45

标签: angular typescript firebase-realtime-database angular6 angularfire5

有人可以帮助解决此问题吗?我正在通过Firebase制作CRUD应用,而我对ts和firebase还是陌生的。请帮助我,我已经为此工作了好几天。谢谢

我的ts文件:

import { Injectable } from '@angular/core';

import { Item } from './item';
import { AngularFireObject, AngularFireList, AngularFireDatabase } from 'angularfire2/database';
import * as firebase from 'firebase';



@Injectable()
export class ItemService {

  private basePath: string = '/items';

  items: AngularFireList<Item[]> = null;
  item: AngularFireObject<Item> = null;

  constructor(private db: AngularFireDatabase) { }

  getItemsList(query={}): AngularFireList<Item[]> {
    this.items = this.db.list('items', ref => ref.orderByChild('value'));
    return this.items
  }

  // Return a single observable item
getItem(key: string): AngularFireObject<Item> {
  const itemPath =  `${this.basePath}/${key}`;
  this.item = this.db.object(itemPath)
  return this.item
}


createItem(item: Item): void  {
  this.items.push(item)                        <--- here is the error
    .catch(error => this.handleError(error))
}


// Update an existing item
updateItem(key: string, value: any): void {
  this.items.update(key, value)
    .catch(error => this.handleError(error))
}

// Deletes a single item
deleteItem(key: string): void {
    this.items.remove(key)
      .catch(error => this.handleError(error))
}

// Deletes the entire list of items
deleteAll(): void {
    this.items.remove()
      .catch(error => this.handleError(error))
}

// Default error handling for all actions
private handleError(error) {
  console.log(error)
}

}

错误出现在createItem()上,我的控制台看起来像这样

src / app / items / shared / item.service.ts(31,19)中的错误:错误TS2345:“项目”类型的参数无法分配给“项目[]”类型的参数。   类型“ Item”缺少类型“ Item []”中的以下属性:长度,弹出,推入,连续和另外26个。

2 个答案:

答案 0 :(得分:1)

您使用的AngularFire2可用于可观察对象。请阅读AngularFire2的文档。现在您的问题是项目是一个可观察的数组,而不是数组,因此您尝试将值推入错误的类型,如果您尝试将值推入数据库,也无法做到这一点,那么您应该再次阅读文档和了解Angularfire2的工作原理

答案 1 :(得分:0)

尝试在ngOnInit()中分配Observable。

ngOnInit(){
this.items = this.db.list('items', ref => ref.orderByChild('value'))
}