【发布时间】:2021-05-31 18:16:56
【问题描述】:
我创建了一个包含帖子列表的应用,用户可以喜欢/不喜欢帖子。对于类似的功能,我使用了 SignalR 并且一切正常,但是如果登录的用户已经喜欢了某个帖子,我想更改点赞按钮的颜色,以便他知道他喜欢哪些帖子。我试过这样做: html
<button id="like" (click)="liked(post)" class="btn liked mr-5">Like<em class="fa fa-thumbs-up"></em> {{post.likes.length}}</button>
打字稿
@Input() post: Post;
button = document.getElementById('like')
constructor(private postService: PostsService)
liked(post: Post) {
const user: User = JSON.parse(localStorage.getItem('user'));
const id = this.getDecodedToken(user.token).nameid;
if(this.post.likes.includes(parseInt(id))) {
this.button.style.color = "red"
}
this.postService.setLike(parseInt(id), post.id);
}
这不起作用。我在控制台中收到错误消息,说 TypeError: Cannot read property 'style' of null 和 this.post.likes.includes(parseInt(id)) 即使当前用户喜欢该帖子,也会返回 false。我从后端发送喜欢列表,我的 Like 类包含一个 ID、一个帖子 ID 和一个用户 ID。这就是 this.post.likes 在控制台中的显示方式,基本上我要做的是验证当前用户的 id 是 18 还是 5,如果有,like 按钮必须是红色的。
0: {id: 13, created: "0001-01-01T00:00:00", user: null, userId: 18, post: null, …}
1: {id: 1026, created: "2021-05-22T12:46:02.811552", user: null, userId: 5, post: null, …}
length: 2
__proto__: Array(0)
【问题讨论】:
标签: angular typescript