类似SignalR的功能不起作用



我创建了一个类似的功能,这样用户就可以喜欢我的应用程序中的帖子。我读过SignalR,并尝试过使用它,这样每当用户点赞/取消点赞帖子时,点赞数量都可以实时自动更新。然而,它不起作用,但我也没有收到任何错误。按下类似按钮后,我控制台中唯一的消息是:

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。

我强烈建议从仔细重写这个例子开始,这确实有助于更好地理解概念https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-5.0&tabs=visual studio

所以,这段代码中有几个问题。PostsService的createLike方法应该只负责通过现有连接进行后调用。所有其他负责连接启动的代码都应该已经执行完毕。https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-5.0#连接到集线器

因此,如果你不熟悉反应式编程和rxjs,我建议你在PostsService中添加一些方法,比如ConnectHubs((:承诺在实际调用一些hub方法之前准备好你的hub连接。

connectHubs() { 
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) => {
// some logic to handle invocation
});
})
.catch(error => console.log(error)); 
}
setLike(userId: number, postId: number) {
this.hubConnection.invoke('SetLike', userId, postId);
}
closeHubConnections() {
this.hubConnection.stop();
}

然后,在持有多个帖子的组件中,除了从api请求所有帖子外,您还需要调用这个connectHubs方法,并等待这个承诺显示所有帖子,以避免在可能之前设置点赞。在这种情况下,最好也停止ngOnDestroy中的连接,以避免从一个客户端到同一集线器的不必要的多个活动连接。或者,您可以在非常基本的组件中调用这个init方法,比如应用程序组件,在这种情况下,您不需要在ngOnDestroy中停止连接,但您需要确保您的用户在建立连接之前登录。也许你可以找到一些组件,在那里它被销毁的情况很少见,但它总是在登录后打开

如果你知道rxjs,你可以添加一些BehaviorSubject字段,比如

private isConnectedSubject = new BehaviorSubject(false);
isConnected$ = isConnectedSubject.asObservable();

然后,您可以添加类似isConnectedSubject.next(true(的内容,而不是在连接启动时返回promise;在断开连接的方法中,您可以添加isConnectedSubject.next(false(;在您的组件中,当集线器未以这种方式连接时,您可以禁用类似按钮:

<button [disabled]="!(postService.isConnected$ | async)" ...>

为了让您的控件知道这个hub中的更改,如果您知道RxJS,您可以添加一些Subject字段及其Observable字段,并在每次收到新消息时发布事件。或者,您可以使用事件发射器使其更简单https://angular.io/api/core/EventEmitter,如下方

服务:

likeMessageReceive = new EventEmitter<{ numOfLikes, postId, userId }>();
connectHubs() {
....
this.hubConnection.on('ReceiveMessage', (numOfLikes, postId, userId) => {
likeMessageReceive.emit({ numOfLikes, postId, userId })
console.log(numOfLikes);
})
....

后置组件:

likesSubscription: Subscription;
ngOnInit() {
this.likesSubscription = this.postsService.likeMessageReceive.subscribe(result =>{
if (result.postId === this.post.id) {
this.post.likes.length = numOfLikes;
}
})
}
liked(post: Post) {
const user: User = JSON.parse(localStorage.getItem('user'));
this.postService.setLike(user.id, post.id);
}
ngOnDestroy() {
if (this.likesSubscription) {
this.likesSubscription.unsubscribe();
}
}

有了rxjs,情况会很一样,但您将使用Subject而不是发射器,不要忘记取消订阅,以避免意外行为和泄漏。

相关内容

最新更新