我正在与Angular 5建立一个实时聊天网站 它适用于用户发送消息,但其他客户端在没有刷新的情况下将无法获取新消息。 后端是NodeJS,它的工作正常,与插座相同 聊天不令人耳目一新是这里的问题。
chat.component.ts:
import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
import { ChatService } from '../services/chat.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css'],
providers : [ChatService]
})
export class ChatComponent {
messages: string[] = [];
constructor(private socket: Socket, private chatservice: ChatService) {
this.socket.on('getOldChat', (data) => {
this.messages.push(data);
});
}
ngOnInit() {
this.chatservice.onMessage()
.subscribe((message: string) => {
console.log('Pushing new msg: '+message);
this.messages.push(message);
});
}
sendChat(chatmessage) {
if (!chatmessage) {
console.log('Blank Message!');
return;
}
console.log('Sending new message: ' + chatmessage);
this.socket.emit('sendChat', chatmessage);
}
}
chat.component.html:
<div *ngFor="let message of messages"><li class="chatmessage">{{ message }}</li></div>
chat.service.ts:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Socket } from 'ng-socket-io';
@Injectable()
export class ChatService {
constructor(private socket: Socket) { }
public onMessage(): Observable<string> {
return new Observable<string>(observer => {
this.socket.on('getChat', (data: string) => observer.next(data));
});
}
}