Reputation: 2013
I'm using AngularFire with Firebase and am wanting to get the key of the element that I just added via the $add()
method. There's a documented way to do this with "vanilla" Firebase, see "Getting the Unique ID Generated by push()" here. It doesn't seem to work with AngularFire's equivalent of $id
, though.
var ref = $firebase(firebaseData.ref()).$asArray();
var newItem = ref.$add({fruit: "apple", color: "red"});
var itemId = newItem.$id;
// Do stuff with itemID...
newItem
is successfully added to Firebase with a new key (such as -Jf-06c0QX_vMMNL3Aek
), but itemId
returns undefined.
Is there a way to do this?
Upvotes: 2
Views: 2487
Reputation:
Now push
returns a Promise
, so its even easier to get the key:
constructor(private afDb: AngularFireDatabase) { }
my_items$ : FirebaseListObservable<Item[]> = this.afDb.list('my-node');
this.my_items$.push(this.item).then((item) => {
console.log(item.key);
});
Upvotes: 1
Reputation: 598857
From the AngularFire documentation for $add:
var list = $firebase(ref).$asArray();
list.$add({ foo: "bar" }).then(function(ref) {
var id = ref.key();
console.log("added record with id " + id);
list.$indexFor(id); // returns location in the array
});
If you're on an older version of AngularFire, that method might still be called name
so then you'd need var id = ref.name();
.
Upvotes: 7