Handeling Error when using push(data) Angularfire2

…衆ロ難τιáo~ 提交于 2019-12-02 13:35:15

问题


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


来源:https://stackoverflow.com/questions/48490508/handeling-error-when-using-pushdata-angularfire2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!