发射的广播数据未显示在组件中

时间:2019-01-09 18:49:27

标签: javascript node.js angular socket.io

从客户端到服务器的发射正常,但从服务器到客户端的发射不正常。

我已经设置了房间,房间数据正在从客户端传递到服务器。

代码结构如下 server.js (这是node.js在Angular中提供聊天服务 app.component 的文件

server.js

io.on('connection', (socket) => {
    console.log('New user connected!');

    socket.on('join', (data) => {
        socket.join(data.room);
        console.log(Date() , ": " + data.user + " has joined " + data.room);

        socket.broadcast.to(data.room).emit('new-user-joined', {user: data.user, message:'has joined room'});
    });
});

chat.service.ts

private url = 'http://localhost:3000';
private socket;

constructor() {
    this.socket = io(this.url);
}

public joinRoom(data) {
    console.log(data);
    this.socket.emit('join', data);
}

public newUserJoined() {
    let observable = new Observable<{user: String, room: String}>((observer) => {
        this.socket.on('new-user-joined', (data)=>{
            console.log(data);
            observer.next(data);
        });
        return () => { this.socket.disconnect(); }
    });
    console.log(observable);
    return observable;
}

app.component.ts

user: String;
room: String;

messageArray: Array<{user: String, message: String}> = [];

constructor(private _chat: ChatService) {
  this._chat.newUserJoined().subscribe((data) => {
    console.log(data);
  });
}

join() {
  this._chat.joinRoom({user:this.user, room:this.room});
}

这里来自join()函数的数据正在工作,但是在调用newUserJoined()时却没有, Observable {_isScalar: false, _subscribe: ƒ},甚至不在Observable内执行console.log

0 个答案:

没有答案