0

Can someone please help to fix this? I'm making CRUD app via firebase and i'm new to ts and firebase. Help me please i'm working on this for days. Thanks

My ts file:

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

}

Error is on the createItem() and my console look like this

ERROR in src/app/items/shared/item.service.ts(31,19): error TS2345: Argument of type 'Item' is not assignable to parameter of type 'Item[]'. Type 'Item' is missing the following properties from type 'Item[]': length, pop, push, concat, and 26 more.

Darko
  • 75
  • 1
  • 9
  • The message says it all: Argument of type 'Item' is not assignable to parameter of type 'Item[]'. The push method expects an Item[], i.e. an array of items. But you're passing an Item as argument, i.e. a single Item, not an array. – JB Nizet Apr 21 '19 at 20:14

2 Answers2

1

AngularFire2 that you used works with observables. read the documentations of AngularFire2 please. Now your problem is that items is an observable and not array so you are trying to push values to the wrong type, also if you trying to push to the databases this is not the way to do it, and again you should read the documentations and learn how Angularfire2 works

Lagistos
  • 3,539
  • 1
  • 10
  • 18
0

Try assigning the Observable in ngOnInit(). Something like

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

Josie G. Bigler
  • 367
  • 4
  • 14