微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 SignalR

如何解决使用 SignalR

我创建了一个带有帖子列表的应用,用户可以喜欢/不喜欢帖子。对于喜欢的功能,我使用了 SignalR 并且一切正常,但是如果登录用户已经喜欢某个帖子,我想更改喜欢按钮的颜色,以便他知道他喜欢哪些帖子。如果用户没有点赞某个帖子,点赞按钮将为灰色,否则为橙色。我试过这样做,使用基于布尔值 isActive 的 ngClass:

<button (click)="liked(post)" class="btn liked mr-5">Like <em [ngClass]="[isActive ? 'my-color' : 'active-color']" class="fa fa-thumbs-up"></em> {{post?.likes.length}}</button>
.my-color {
  color: grey;
}

.active-color {
  color: #e08e23;
}

export class PostCardComponent implements OnInit,OnDestroy {

  @input() post: Post;
  isActive = false;

 constructor(private postService: PostsService) {}

 ngOnInit(): void {
    this.postLiked();

    this.likesSubscription = this.postService.likeMessageReceive.subscribe(result =>{
      
        if ( result.postId ===  this.post.id) {
            this.post = result.numOfLikes;
        }
  })

    this.route.params.subscribe((params) => {
      this.postId = params['id'];
    });
}

postLiked() {
    const user: User = JSON.parse(localStorage.getItem('user'));
    const id = this.getDecodedToken(user.token).nameid;
    var checkLike = this.post.likes.filter(like => (like.userId === parseInt(id)));
    console.log(checkLike);
    if(checkLike.length === 0) {
      this.isActive = true;
    }
    return this.isActive;
  }

  liked(post: Post) {
    const user: User = JSON.parse(localStorage.getItem('user'));
    const id = this.getDecodedToken(user.token).nameid;
    
    this.postService.setLike(parseInt(id),post.id)
    .then(() => {
      this.postLiked();
    });
  }
}

使用 SignalR 构建的类似功能如下所示:

 private hubConnection: HubConnection;
 likeMessageReceive: EventEmitter<{ numOfLikes: Post,postId: number,userId: number }> = new EventEmitter<{ numOfLikes:Post,userId: number }>();


 connectHubs(user: User) { 
      this.hubConnection = new HubConnectionBuilder()
      .withUrl(this.hubUrl + 'like',{ accesstokenFactory: () => user.token,skipNegotiation: true,transport: signalR.HttpTransportType.WebSockets })
      .build();
  
      return  this.hubConnection.start()
                 .then(() => {
                     this.hubConnection.on('ReceiveMessage',(numOfLikes,postId,userId) => {
                      user.id = userId;
                       this.likeMessageReceive.emit({ numOfLikes,userId });
                     });
                 })
                 .catch(error => console.log(error)); 
  }
  
  setLike(userId: number,postId: number) {
     return this.hubConnection.invoke('SetLike',userId,postId);
  }

后端:


        public async Task SetLike(int userId,int postId)
        {
            Like l = new Like();

            Like temp = _context.Likes.Where(x => x.PostId == postId && x.UserId == userId).FirstOrDefault();

            if(temp != null)
            {
                _context.Likes.Remove(temp);
            } else
            {

                l.UserId = userId;
                l.PostId = postId; 

                _context.Likes.Add(l);

            }

            await _context.SaveChangesAsync();

            var post = await _postRepository.GetPostAsync(postId);

            await Clients.All.SendAsync("ReceiveMessage",post,userId);

        }

当我不喜欢某个帖子时,按钮会立即从橙色变为灰色并按需要工作。然而,反过来说,如果我喜欢一个帖子,按钮只会在刷新页面后从灰色变为橙色,而不是立即。这是为什么?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。