Here I have a code (backend SpringBoot, frontend Angular):
constructor(private catDocumentBackendService: CatDocumentBackendService,
private activatedRoute: ActivatedRoute,
private websocketService: WebSocketService,
private authenticationService: AuthenticationService,
private formBuilder: FormBuilder,
public dialog: MatDialog) {
this.getNotes();
this.stompClient = this.websocketService.getStompClient();
}
ngAfterViewInit() {
this.stompClient.connect(this.websocketService.getHeaders(), () => {this.subscribeStomp()});
}
subscribeStomp() {
// Add a note
this.addNoteSubscription = this.stompClient.subscribe('/user/queue/document/add', (data: { body: string; }) => {
const body = JSON.parse(data.body);
const newNote = body.body;
this.notes$.pipe(
concatMap(notes => {
return of([...notes, newNote]);
})
).subscribe(updatedNotes => {
this.notes$ = of(updatedNotes);
});
console.log("Notified!");
this.selectNote(newNote);
}, (error: any) => {
console.error('Erreur lors de la connexion au WebSocket:', error);
});
// Delete a note
this.deleteNoteSubscription = this.stompClient.subscribe('/user/queue/document/delete', (data: { body: string; }) => {
console.log(data);
console.log("DELETED");
this.selectedNote = undefined;
}, (error: any) => {
console.error('Erreur lors de la connexion au WebSocket:', error);
});
}
selectNote(note: Note) {
this.selectedNote = note;
this.noteSubscription = this.stompClient.subscribe('/user/queue/document/' + this.selectedNote!.id + "/update", (data: {
body: string;
}) => {
const note = JSON.parse(data.body);
const updatedNote = note.body as Note;
console.log(updatedNote);
this.updateSelectedNoteInNotes(updatedNote);
});
Sometimes it works, sometimes it doesn't. I need to refresh several times my page until it works at some point. I don't have any error, it just doesn't subscribe. And sometimes, when it subscribes, I just have to click on a note and it disconnects automatically. "Connection closed to http://localhost:8080/ws"
Is there a better way to do it? I've tried to put the connect method in the constructor and in ngOnInit but it seems like in ngAfterViewInit is the less worse scenario.
Should I keep doing this with StompJS or should I use Socket.IO ?
Thanks for your help