Get list of items from Firebase with their key

I have a list of tasks that I’m saving from Firebase using push() which generates an automated id

createTask(task: Task){
    let uid = task.uid;
    return firebase.database().ref().child(`/tasks/${uid}`).push(task)
    .then(() =>{
      /* add task to SQLite */
    }, err =>{
      console.log('rejected');
    })
  }

And here is where I retrieve those tasks, firedb is an AgularFireDatabase object.

return this.firedb.list(`/tasks/${this.uid}`).valueChanges();

I wanna get the list of tasks together with the associated key for each task, so that I can be able to pass that key or id to the function below

getTaskById(taskId){
    return firebase.database().ref().child(`/tasks/${this.uid}/${taskId}`)
    .once('value')
    .then(snapshot =>{
      console.log(snapshot.val());
    })
  }

Thanks

I sorted it out. Although I feel there’s a much cleaner and easier way of doing this.
I decided to write the data and get key property of push() and run an update() inserting the key as the taskid. That way when I get a list of tasks, I also get their key.

createTask(task: Task){
    let uid = task.uid;
    let key = this.ref.child(`/tasks/${uid}`).push(task).key;
    task.taskid = key;
    return this.ref.child(`/tasks/${uid}/${key}`)
    .update(task);
  }
1 Like