Handeling Error when using push(data) Angularfire2

2020-04-18 06:32发布

问题:

How to handle Error when pushing data with angularFire2?

I used the following method:

todoLists: AngularFireList<TodoList>;

addList(data): ThenableReference {

    const item: Item = {
      name: data.task,
      state: false,
      description: 'No description'
    };
    const todoList: TodoList = {
      id: '',
      name: data.name,
      items: [item]
    };
    this.todoLists.push(todoList).then(_ => this.presentToast('List succesfuly added'))
                               .catch(err => _ => this.presentToast('Something wrong happened'));
  }

The problem here is that the push method of AngularFire returns an ThenableReference so the catch method doesn't exist in that interface.

Here's the message from the editor (vscode)

property catch doesn't exist on type promiseLike<> There must another way to handle errors.

回答1:

I had the same problem, and I found I could create the thenable reference with the push() method, then use set which returns an error on .catch.

See more here in the docs.

todoLists: AngularFireList<TodoList>;

addList(data): void {
  const item: Item = {
    name: data.task,
    state: false,
    description: 'No description'
  };
  const todoList: TodoList = {
    id: '',
    name: data.name,
    items: [item]
  };

  // .push() also creates a new unique key, which can be accessed with ref.key
  let ref: Reference = this.todoLists.push(); 
  ref.set(todoList)
    .then( () => this.presentToast('List succesfuly added'))
    .catch(err => this.presentToast('Something wrong happened: ' + err));
}