服务端(nodeJs/express):
io.on('connection',(socket) => {
console.log('user connected');
console.log('user connected');
socket.on('disconnect',function(){
console.log('user disconnected');
});
socket.on('add-message',(message) => {
io.emit('message',{type:'new-message',text: message});
});
});
http.listen(5000,() => {
console.log('started on port 5000');
});
客户端,创建一个ChatService
export class ChatService {
private url = 'http://localhost:5000';
private socket;
private url = 'http://localhost:5000';
private socket;
sendMessage(message){
this.socket.emit('add-message',message);
}
getMessages() {
let observable = new Observable(observer => {
this.socket = io(this.url);
this.socket.on('message',(data) => {
observer.next(data);
});
return () => {
this.socket.disconnect();
};
})
return observable;
}
}
ChatComponent
@Component({
moduleId: module.id,selector: 'chat',template: `<div *ngFor="let message of messages">
{{message.text}}
moduleId: module.id,selector: 'chat',template: `<div *ngFor="let message of messages">
{{message.text}}