Reputation: 483
I am trying to implement user like/unlike function in ionic 2. The idea is simply to click the like button to toggle like/unlike status.
likeItem(itemId) {
let objRef = this.af.database.object('userItemCollection/'+this.userId+'/items/'+itemId);
objRef.subscribe(snapshot => {
if(snapshot.$value) {
objRef.remove();
} else {
objRef.set(true);
}
});
}
However, once I click the like button and trigger the function, I can see in the Firebase console, it adds many records to the database. I am not sure where I go wrong.
Upvotes: 1
Views: 1174
Reputation: 3433
You can do this by using the Observable take method::
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/take'
likeItem(itemId) {
let objRef = this.af.database.object('/item/itemId', { preserveSnapshot: true })
objRef.take(1)
.subscribe(snapshot => objRef.set({like: !snapshot.val().like}))
}
I hope this solves your question :)
Upvotes: 2