William Wu
William Wu

Reputation: 483

Implement like/unlike function in ionic 2 with firebase

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

Answers (1)

DauleDK
DauleDK

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

Related Questions