I've been working on implementing a like functionality in my project, but I've hit a roadblock. Essentially, what I'm trying to achieve is this: when a user clicks the like button, it should change the color of the like icon (fill it) and display the number of likes dynamically. Even after refreshing the page, I want the 'filled' like button to remain visible, like in this image:
https://i.sstatic.net/BEPX9.png
The initial part of the implementation seems to be working fine, but upon page reset, it reverts back to its original state as shown here:
https://i.sstatic.net/zz22J.png
Is there a way to ensure that if a user refreshes the browser, a previously liked post remains liked, and if it's already liked and clicked again, it unlikes? Here's some sample code I've tried so far:
HTML
<div class="likes">
<div *ngIf="!isLiked">
<i class="fa fa-heart-o" (click)="likeTweet(tweet.id)"></i>
</div>
<div *ngIf="isLiked">
<i class="fa fa-heart" (click)="unlikeTweet(tweet.id)"></i>
</div>
<div class="likes-count">
{{getLikes}}
</div>
</div>
Component
isLiked: boolean = false;
like: Like = new Like();
likeTweet(tweetId: number){
this.likeService.likeTweet(tweetId, this.like).subscribe(response => {
this.like = response;
this.isLiked = true;
});
}
unlikeTweet(tweetId: number){
this.likeService.unlikeTweet(tweetId).subscribe(response => {
console.log(response);
this.isLiked = false;
});
}
getTweetLikes(){
const tweetId = this.route.snapshot.params['tweetId'];
this.likeService.getTweetLikes(tweetId).subscribe(response => {
this.likes = response;
})
}
likes: LikeModel[];
get getLikes(){
return this.likes.length;
}
Service
url: string = environment.apiBaseUrl; // localhost:8080
constructor(private http: HttpClient) { }
likeTweet(tweetId: number, like: Like){
return this.http.post<Like>(`${this.url}/like/tweet/${tweetId}`,like);
}
unlikeTweet(tweetId: number){
return this.http.delete<Like>(`${this.url}/unlike/tweet/${tweetId}`);
}
getTweetLikes(tweetId: number){
return this.http.get<LikeModel[]>(`${this.url}/tweet/${tweetId}/likes`);
}
Entities
export class Like {
id: number;
likedTweet: Tweet;
likedComment: Comment;
user: User;
}
export class LikeModel {
username: string;
}
relationship https://i.sstatic.net/1Kpqd.png