某些组件的Angular2 socket.io单例websocket服务
你好 在angular2上编写聊天时遇到问题。 使用库socket.IO 获取websocket服务使用的数据 在其中导入多个组件 接收到的新消息的组件 当服务器将它们发送到客户端时 chatservice2.service.ts某些组件的Angular2 socket.io单例websocket服务,angular,service,websocket,socket.io,singleton,Angular,Service,Websocket,Socket.io,Singleton,你好 在angular2上编写聊天时遇到问题。 使用库socket.IO 获取websocket服务使用的数据 在其中导入多个组件 接收到的新消息的组件 当服务器将它们发送到客户端时 chatservice2.service.ts import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable, Observer } from 'rxjs/Rx
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable, Observer } from 'rxjs/Rx';
import * as io from 'socket.io-client';
@Injectable()
export class ChatService {
private url:string = 'http://websocketserver:1080/';
private socket;
sendMessage(message) {
this.socket.emit('add-message', message);
}
getMessages() {
let observable = new Observable(observer => {
if (!this.socket) {
console.log('create ws connection');
let connectionOptions = {
'reconnection': true,
'reconnectionDelay': 10000, //milliseconds
'reconnectionDelayMax' : 15000, //milliseconds
'reconnectionAttempts': 30
};
this.socket = io(this.url, connectionOptions);
}
this.socket.on('message', (data) => {
console.log('chatservice2.service next message observer', data, observer);
observer.next(data);
});
return () => {
this.socket.disconnect();
};
});
return observable;
}
}
dialog.component.ts
//...
import { ChatService } from '../chatservice2.service';
//...
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css'],
providers: [HttpService]
})
//...
export class DialogComponent implements OnInit {
private wsChannel$;
constructor(
private chatService: ChatService
) {}
ngOnInit() {
console.log('dialog component ngOnInit');
this.wsChannel$ = this.chatService
.getMessages()
.subscribe(message => {
console.log('message dialog.component', message);
this.someFunc(message);
//...
});
}
ngOnDestroy() {
this.wsChannel$.unsubscribe();
}
//...
}
如果您第一次打开组件(dialog.component.ts)。
消息来了。一切都好。
如果导航到另一个组件。
然后返回到dialog.component.ts消息将停止出现,即24行控制台。log('message dialog.component',message)将不会触发。
如果删除此.wsChannel$.unsubscribe();(第32行)在方法Ngondestry中,在component dialog.component.ts控制台中的2次转换后,将触发2次,一次用于来自服务器的传入websocket消息。如果您使用10拉功能,控制台将在一条websocket消息上触发10次。
问题是我如何修复它?如何让unsubscribe方法在保留组件的同时工作,来自chatservice2.service.ts的消息不会重复。我犯了什么错?
提前谢谢你的帮助