【发布时间】:2021-05-03 02:51:12
【问题描述】:
我创建了一个点赞功能,以便用户可以点赞我的应用中的帖子。我已经阅读了 SignalR 并尝试使用它,以便在用户喜欢/不喜欢帖子时实时自动更新喜欢的数量。但是,它不起作用,但我也没有收到任何错误。按下like按钮后,我控制台中的唯一消息是:
Information: WebSocket connected to wss://localhost:44351/hubs/like?access_token=eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIxIiwidW5pcXVlX25hbWUiOiJnZW9yZ2lhIiwicm9sZSI6WyJNZW1iZXIiLCJBZG1pbiJdLCJuYmYiOjE2MTk0NjQ3NzAsImV4cCI6MTYyMDA2OTU3MCwiaWF0IjoxNjE5NDY0NzcwfQ.1Bwf_Y2QJP_VjRUXaBeqz5sueV6oTIpVlOLU4kOEmLf2Y_hfxJbc5_f4yksY9R45YGz0qPWw-rc10I7pobFJYQ
这是我的 .net 代码:
public class LikeHub : Hub
{
private readonly IPostRepository _postRepository;
private readonly DataContext _context;
private readonly IUserRepository _userRepository;
public LikeHub(IPostRepository postRepository, DataContext context, IUserRepository userRepository)
{
_postRepository = postRepository;
_context = context;
_userRepository = userRepository;
}
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
{
_context.Likes.Add(l);
l.UserId = userId;
l.PostId = postId;
}
await _context.SaveChangesAsync();
int numOfLikes = _context.Likes.Where(x => x.PostId == postId).Count();
await Clients.All.SendAsync("ReceiveMessage", numOfLikes, postId, userId);
}
}
这是我在 PostsService 中的 Angular 代码:
export class PostsService {
hubUrl = environment.hubUrl;
private hubConnection: HubConnection;
likeMessageReceive: EventEmitter<{ numOfLikes: number, postId: number, userId: number }> = new EventEmitter<{ numOfLikes:number, postId: number, userId: number }>();
constructor(private http: HttpClient) {}
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) => {
this.likeMessageReceive.emit({ numOfLikes, postId, userId });
});
})
.catch(error => console.log(error));
}
setLike(userId: number, postId: number) {
this.hubConnection.invoke('SetLike', userId, postId);
}
closeHubConnections() {
this.hubConnection.stop();
}
}
这是我的 PostCardComponent 中的 Angular 代码,其中点赞按钮是:
export class PostCardComponent implements OnInit {
@Input() post: Post;
likesSubscription: Subscription;
constructor(private postService:PostsService,public accountService:AccountService)
{ this.Login$ = this.accountService.Logged;}
ngOnInit(): void {
this.likesSubscription = this.postService.likeMessageReceive.subscribe(result =>{
if (result.postId === this.post.id) {
this.post.likes.length = result.numOfLikes;
}
})
}
liked(post: Post) {
const user: User = JSON.parse(localStorage.getItem('user'));
this.postService.setLike(user.id, post.id);
}
}
这是 PostListComponent,所有的帖子都在这里:
export class PostListComponent implements OnInit {
posts: Post[];
post: Post;
likesSubscription: Subscription;
localUser: User;
constructor(private postService: PostsService) {}
ngOnInit(): void {
this.postService.connectHubs(this.localUser);
}
}
不知道this.hubConnection.on()中的代码是否正确,或者给定的参数是否正确。我还在 Startup.cs 类的端点中添加了 LikeHub。
【问题讨论】:
-
您能否在 on 处理程序中添加 console.log(numOfLikes) 并查看您收到了什么?你是什么意思它不起作用?数据库更新了吗?另外,你为什么用喜欢的用户的 id 更新用户 id?
-
数据库未更新。 userId 是点赞帖子的用户 ID,postId 是点赞帖子的 ID。如果我写console.log(numOfLikes),没有数据显示,断点甚至没有到达那个点。可能是因为我用过then()?
-
哦,真的,甚至没有注意到 :D 在你制作 HubConnectionBuilder().**.build() 之后,尝试将这个 .on 监听器向上移动
-
传递给createLike()方法的user和post参数发送正确。我已经更新了代码,并将 connectionHub.on() 与 connectionHub.start() 分开。现在断点到达connectionHub.on(),但还是没有到达conole.log(numOfLikes)
-
我在构建之后移动了 .on,但结果仍然相同。我可能需要在后端使用 Clients.Caller.SendAsync() 吗?
标签: asp.net angular signalr signalr-hub