0

I have this following button:

 <button mat-button 
         (click)="toggleLikeQuestion(question['id'])" aria-label="Like this question.">
         {{!isQuestionLiked(question) ? 'Like' : 'Unlike'}}
 </button> 

And this is the action when it's clicked:

public isQuestionLiked = (q): boolean => q['likedBy'].some(s => s['id'] === this.studentId);

  toggleLikeQuestion(id: string) {
    this.questionService.getQuestion(id).subscribe((question) => {
      const isLiked = this.isQuestionLiked(question);
      if (question) {
        if (!isLiked) {
          this.questionService.likeQuestion(id, this.student).subscribe(() => this.questionService.getQuestion(id));
        } else {
          this.questionService
            .unlikeQuestion(id, this.student)
            .subscribe(() => this.questionService.getQuestion(id));
        }
      }
    });
  }

This works, the only thing is that the button does not update its content (Like or Unlike) after the subscribe function is called after like or un-liking the question. It only updates when I reload the site. What should I do to make it updates without reload the site?

The get question function is http method, so it's an Observable, then it would become nested observable, I'm not sure if that causes the issue. Thank you.

0

1 Answer 1

2

After subscribing, you are again calling this.questionService.getQuestion(id) which only returns an observable and has no effect. An observable has effect only if it is subscribed.

I would suggest you to do the get request in ngOnInit and save it in an array questions. Then when the user likes a question, you can find the question in the array and change the value accordingly and then send a put/patch request to the backend.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.