Home Ask Login Register

Developers Planet

Your answer is one click away!

sushil bharwani February 2016

Managing an Array of Likes in AngularJS Service

I have a like Button on Profile Page, On click of Like Button i want to maintain an array of like and store it into my db.

in profile Controller I have

$scope.likeProfile = UserService.likeProfile(loggedInUser,$state.params.userId);

In User Service I have

function likeProfile(likedBy,id){
   var likeArray = [];
   ref.child("users").child(id).update({ likedBy: likeArray});

I just want to understand how I could not intialize likeArray everyTime LikeProfile Method is called. So that all likes are pushed into array.


lisa p. February 2016

I would do it like this, not sure though if this is what you want to achieve. Initialization should not be done within the function if you want to keep the result. This keeps the result within the scope of one user.

$scope.likeArray = [];

function likeProfile (likedBy, id) {
    ref.child("users").child(id).update({ likedBy: likeArray});

Otherwise, if you need overall likes you have to initialize the array with the previous values within the function, sth. like

likeArray = getLikesFromDB();   // however you access your db
ref.child("users").child(id).update({ likedBy: likeArray });

Try to debug with the browser dev tools (e.g. in Chrome Tools > Developer Tools) and see what you send in the network tab. If your array only contains one value the whole array will be overwritten unless you write a custom update function that adds a value rather than replaces the value.

Post Status

Asked in February 2016
Viewed 3,098 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life