Angular5:socket.on函数中的服务未定义

时间:2018-06-07 10:32:47

标签: javascript angular5 socket.io-1.0

我正在尝试使用angular5应用程序中的socket.io实现聊天。

Component.ts

export class ChatComponent implements OnInit {
    private socket: SocketIOClient.Socket;
    constructor(
        private chatService: ChatsService
    )

    ngOnInit() {
        this.socketInit();
    }

    socketInit() {
        this.socket.on('chat', function(data) {
            console.log("message", data);
            this.chatService.chats.userChats.push({
                message: data.message
            });

        });
    }
}

服务

@Injectable()
export class ChatsService {
    chats: any = {
        userInfo: {},
        userChats: [],
    };
}

socket.on我得到了值,但问题在于推送

this.chatService.chats.userChats.push({
    message: data.message
});
  

无法阅读财产'聊天'未定义的

同样this.chatServicesocket.on

中是不可取的

0 个答案:

没有答案