【问题标题】:How to fix 'Item' is missing the following properties from type 'Item[]': length, pop, push, concat, and 26 more如何修复“项目”缺少类型“项目 []”中的以下属性:长度、弹出、推送、连接等 26 个
【发布时间】:2019-09-11 04:07:34
【问题描述】:

有人可以帮忙解决这个问题吗?我正在通过 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[]”类型的参数。 “Item”类型缺少“Item[]”类型的以下属性:length、pop、push、concat 等 26 个。

【问题讨论】:

  • 消息说明了一切:“Item”类型的参数不可分配给“Item[]”类型的参数。 push 方法需要一个 Item[],即一个项目数组。但是您将 Item 作为参数传递,即单个 Item,而不是数组。

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


【解决方案1】:

您使用的 AngularFire2 适用于可观察对象。请阅读 AngularFire2 的文档。现在你的问题是 items 是一个可观察的而不是数组,所以你试图将值推送到错误的类型,如果你试图推送到数据库,这不是这样做的方法,你应该再次阅读文档和了解 Angularfire2 的工作原理

【讨论】:

    【解决方案2】:

    尝试在 ngOnInit() 中分配 Observable。像

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-04
      • 2022-11-28
      • 2021-02-15
      • 2020-07-20
      • 2019-06-25
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      相关资源
      最近更新 更多