【发布时间】:2017-05-03 15:52:03
【问题描述】:
我将 Angular2 webapp 项目用于 FRONT-END 和 Vertex3 用于 BACK-END。
使用 Sockjs-client 我正在创建 websocket(在客户端)来创建前端和后端之间的通信通道。
我已经使用 npm 安装了 sockjs-client:
npm install sockjs-client
当我在 LoginService.ts 文件中导入 sockjs-client 时:
从 'sockjs-client' 导入 * 作为 SockJS;
export class LoginService {
URL: string = 'http://localhost:8082/eventbus';
sock: SockJS;
handlers = {};
private _opened: boolean = false;
public open(): void {
if (!this._opened) {
this.sock = new SockJS(this.URL);
this.sock.onopen = (e) => {
this.callHandlers('open', e);
}
this.sock.onmessage = (e) => {
this.messageReceived(e);
}
this.sock.onclose = (e) => {
this.callHandlers('close', e);
}
this._opened = true;
}
public isOpen(): boolean {
return this._opened;
}
public close(): void {
if (this._opened) {
this.sock.close();
delete this.sock;
this._opened = false;
}
}
private messageReceived (e) {
var msg = JSON.parse(e.data);
this.callHandlers('message', msg.type, msg.originator, msg.data);
}
private callHandlers (type: string, ...params: any[]) {
if (this.handlers[type]) {
this.handlers[type].forEach(function(cb) {
cb.apply(cb, params);
});
}
}
public send (type: string, data: any) {
if (this._opened) {
var msg = JSON.stringify({
type: type,
data: data
});
this.sock.send(msg);
}
}
}
使用 angular2 webapp 项目运行时没有错误
npm 运行服务器
但是在客户端没有创建 websocket 连接。因为我已经使用顶点vertex.createHttpServer(托管在:http://localhost:8082)创建了服务器。
所以我有两个问题:
1.在angular2 webapp中无法导入sockjs-client,所以无法创建websocket连接。
2. 构建 angular2 webapp 项目时出错,因为在 node_modules 中找不到“sockjs-client”(奇怪的是它存在于 node_modules 中)
我有什么遗漏吗?
提前致谢!!!
【问题讨论】:
标签: angular typescript websocket vert.x sockjs