错误TypeError:无法读取null的属性“push”

时间:2017-07-11 16:39:10

标签: javascript angular firebase firebase-realtime-database angularfire2

我正在尝试推送到列表并发生以下错误:

import { Injectable } from '@angular/core';
// import { AngularFire, FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase } from "angularfire2";
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Project } from './project'

@Injectable()
export class ProjectService {

  private basePath: string = '/projects';

  //items: FirebaseListObservable<Project[]> = null; //  list of objects
  items: FirebaseListObservable<Project[]> = null; //  list of objects
  item: FirebaseObjectObservable<Project> = null; //   single object

  constructor(private db: AngularFireDatabase) {}

  // Return an observable list with optional query
  // You will usually call this from OnInit in a component
  getItemsList(query={}): FirebaseListObservable<Project[]> {
    this.items = this.db.list('/projects', {
      query: query
    });
    return this.items
  }

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

  // Create a bramd new item
  createItem(item: Project): void  {
    this.items.push(item)
      .catch(error => this.handleError(error))
  }


  // Update an exisiting 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:

  

错误TypeError:无法读取null的属性'push'   在
   ProjectService.webpackJsonp ... / .. / .. / .. / .. / src / app / projects / shared / project.service.ts.ProjectService.createItem(project.service.ts:36)
  在
   ProjectFormComponent.webpackJsonp ... / .. / .. / .. / .. / src / app / projects / project-form / project-form.component.ts.ProjectFormComponent.createItem(project-form.component.ts:20 )
    在Object.eval [as handleEvent](ProjectFormComponent.html:8)
    在handleEvent(core.es5.js:12047)
    at callWithDebugContext(core.es5.js:13508)
    at Object.debugHandleEvent [as handleEvent](core.es5.js:13096)
    at dispatchEvent(core.es5.js:8659)
    在core.es5.js:9270
    在HTMLButtonElement。 (平台browser.es5.js:2668)
    在
  ZoneDelegate.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.ZoneDelegate.invokeTask(zone.js:424)

我已经尝试获取null声明,它会生成另一个未定义的错误。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

我在构造函数中启动了列表:

delimiter