【问题标题】:Confused over how i should use an observable对我应该如何使用 observable 感到困惑
【发布时间】:2021-02-21 00:03:05
【问题描述】:

我正在尝试使聊天成为一个有角度的 node.js 实时聊天应用程序 我正在使用带有角度和 nodejs 后端的 socket.io

服务器端

 io.on('connection', (socket) => {
  socket.on('new-message', (message) => {
    io.emit(message);

  });
}); 

客户端

服务

private url = 'http://localhost:3000';
  private socket;
constructor( private httpClient: HttpClient ) {
    this.socket = io(this.url);
}
 public sendMessage(message:Message){
    this.socket.emit('new-message',message);
  }
 public getMessages = () => {
    return new  Observable(observer => {
        this.socket.on('new-message', (message) => {
            observer.next(message);

        });
    });
}

组件

messages:any[]=[];
constructor(private chatService:ChatService){}
ngOnInit(): void {
  this.chatService.getMessages()
  .subscribe((message:any)=>{
    this.messages.push(message);

  })
onSubmit(){
//extracting message from the input form (not relevant i think i can add it if suggested)
this.chatService.sendMessage(tosend);
}

component.html

<div *ngFor="let m of messages">
 {{m.text}}
</div>
<! -- a form to send messages  -->

【问题讨论】:

  • 这是什么问题?你在哪里得到错误?
  • 那么消息数组总是空的。订阅中的函数永远不会执行

标签: javascript angular typescript socket.io rxjs


【解决方案1】:

原来问题是服务器端必须更改
io.emit(message); 给io.emit('new-message',message)

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2018-12-29
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多