I am trying to implement a like mechanism in my project but I got stuck. Basically I am trying to do this: when the user clicks on the like button, it changes the colour of the like ('fills it') and displays the number of likes dynamically and if the page is refreshed i want it to still display the 'filled' like button like this:
The first part of this problem seems to work fine but after i reset the page it just goes back to this:
How can I make it so if I refresh my browser if it was liked to remain liked, and if its liked and I click it, to unlike? Here's some code I have tried:
HTML
<div >
<div *ngIf="!isLiked">
<i (click)="likeTweet(tweet.id)"></i>
</div>
<div *ngIf="isLiked">
<i (click)="unlikeTweet(tweet.id)"></i>
</div>
<div >
{{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;
}
CodePudding user response:
Ruschisb,
In your function getTweetLikes() you need update property isLiked, because this is ever false.
Thank!