Два дня потрачено...
Суть проблемы: Пишется мини чат на angular с. использованием signalR (бэкенд на c#, restAPI).
Сейчас все работает когда приложение только запустилось, идем по адресу http://localhost:4200/messendger и нормально переписываемся. Как только перешли по другому адресу и вернулись обратно - сообщения в чате начинают дублироваться, если перейти опять на другую страницу и вернуться - то сообщений уже будет +3, ну и так далее.
Подписка на Observable отменяется вроде вовремя. Помогите плиз)
Код сервиса SignnalrService:
import { analyzeAndValidateNgModules } from '@angular/compiler';
import { EventEmitter, Injectable, Output } from '@angular/core';
import { NumberValueAccessor } from '@angular/forms';
import * as signalR from "@microsoft/signalr";
import { Observable, of } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { CommonService } from './common.service';
declare var $: any;
const subject = new Observable<number>();
@Injectable({
providedIn: 'root'
})
export class SignnalrService {
private hubConnection: signalR.HubConnection;
constructor(private commonService: CommonService) {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:5001/chatHub", {
accessTokenFactory: () => {
return this.token;
}
} as signalR.IHttpConnectionOptions)
// .withAutomaticReconnect()
.build();
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
// this.connect();
}
public connect() {
if (this.hubConnection.state === signalR.HubConnectionState.Disconnected) {
this.hubConnection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log(err));
}
}
public disconnect() {
this.hubConnection.stop();
}
private token = localStorage.getItem('token');
private newMessageCount = new BehaviorSubject<number>(0);
public newMessage = new BehaviorSubject<any>(0);
setSpinnerState(): void {
this.newMessageCount.next(Number(this.newMessageCount.value) + 1);
};
public getNewMessageCount(): Observable<number> {
return this.newMessageCount;
};
public getNewMessage(): Observable<any> {
this.hubConnection?.on('NewMessageText', (data) => {
this.commonService.currentCompanyIdJson().subscribe((res: any) => {
if (data.IdCompany == res) {
this.setSpinnerState();
} else {
}
});
this.newMessage.next(data);
return this.newMessage;
});
return this.newMessage;
};
public SendMessageText(message: any) {
this.hubConnection?.invoke("SendMessageText", message)
.then(() => {
});
}
}
Код компонента:
declare var $: any;
@Component({
selector: 'app-messenger',
templateUrl: './messenger.component.html',
styleUrls: ['./messenger.component.css']
})
export class MessengerComponent implements OnInit , OnDestroy {
@ViewChild('mychat') mychat: any;
subscription?: Subscription;
notifier = new Subject();
destroy$: Subject<boolean> = new Subject<boolean>();
constructor(private commonService: CommonService, public messangerServise: MessegerService, private signalRService: SignnalrService) { }
allUsers: any;
myGroups: any[] = [];
myName: any;
messages: any[] = [];
currentIdGroup: any;
currentGroupName: any;
newMessage: any;
myProfile: any;
currentCheckedGroup: any;
ngOnInit(): void {
this.getAllUsers();
this.getMyGroups(1);
this.countHeight();
this.getMyProfile();
this.signalRService.newMessage
.pipe(takeUntil(this.notifier))
.subscribe(data =>{
console.log(data);
});
this.subscription = this.signalRService.getNewMessage()
.pipe(takeUntil(this.notifier))
.subscribe(data => {
if (this.getcurrentCheckedGroup(data.messages?.IdGroup) == -1) {
this.getMyGroups();
}
var countIdGroup = parseInt($("#groupCountId_" + data.messages?.IdGroup).html());
if (isNaN(countIdGroup)) {
countIdGroup = 0;
}
countIdGroup = Number(countIdGroup) + 1;
$("#groupCountId_" + data.messages?.IdGroup).html(countIdGroup);
if (this.currentIdGroup === data.messages?.IdGroup && this.currentIdGroup != null) {
var newMes = {
id: data.messages?.Id,
id_group: data.messages?.IdGroup,
id_tip: data.messages?.IdType,
id_sender: data.messages?.IdSender,
datetime: data.messages?.Datetime,
value: data.messages?.Value,
myid: data.messages?.MyId,
name_user: data.NameUser,
otchestvo: data.Otchestvo,
familia: data.FamilyUser,
val: null
}
this.messages.push(newMes);
setTimeout(function () {
var div = $("#myChat");
div.scrollTop(div.prop('scrollHeight'));
}, 1);
}
});
}
ngOnDestroy() : void {
this.notifier.next();
this.notifier.complete();
this.notifier.unsubscribe();
this.destroy$.next(true);
this.destroy$.unsubscribe();
this.subscription?.unsubscribe();
}
getMyProfile() {
this.commonService.getMyProfile().subscribe(
(res: any) => {
this.myProfile = res;
},
err => {
console.log(err);
this.myProfile = [];
}
);
}
sendMes() {
var txt = $("#message").val();
if (txt == "")
return;
var message = {
IdGroup: this.currentIdGroup,
Value: txt
}
this.signalRService.SendMessageText(message);
$("#message").val('');
$('#message').attr('rows', 1);
var curDate = new Date();
var newMes = {
id: "",
id_group: this.currentIdGroup,
id_type: 1,
id_sender: this.myProfile.id_user,
datetime: curDate,
value: txt,
myid: this.myProfile.id_user,
name_user: this.myProfile.nameUser,
otchestvo: this.myProfile.otchestvo,
familia: this.myProfile.familia,
val: null
}
this.messages.push(newMes);
setTimeout(function () {
var div = $("#myChat");
div.scrollTop(div.prop('scrollHeight'));
}, 1);
}
ReadMessages() {
this.signalRService.ReadMessInGroup(this.currentIdGroup);
}
}
messenger
OnDestroy()
, вдруг компонент не умер.