【问题标题】:WebSockets in angular2angular2中的WebSockets
【发布时间】:2016-04-23 15:05:08
【问题描述】:

我想将 WebSocket 客户端集成到我的 angular2 应用程序中。

我首先尝试使用 sock.js https://github.com/sockjs/sockjs-client 来做到这一点 并像这样创建了一个 SockJS 对象:

export class Core {

  private sock: any;

  constructor (private router: Router) {

    this.sock = new SockJS(AppSettings.WEBSOCK_ENDPOINT);

  }

}

我的问题是 angular2 无法识别 SockJS 类型。

然后我尝试在我的项目中使用https://github.com/retyped/sockjs-client-tsd-ambient/blob/master/sockjs-client.d.ts 提供的类型定义,但无法真正弄清楚在哪里以及如何设置类型。

或者我尝试使用 angular2-websocket npm 包https://github.com/afrad/angular2-websocket,但是当我在我的应用程序中这样做时:

import {$WebSocket} from 'angular2-websocket/angular2-websocket'
var ws = new $WebSocket("url");

我的 IDE (Jetbrains WebStorm) 告诉我 $WebSocket 至少需要 2 个参数。

由于目前关于 angular2 中的 WebSocket 的信息很少,我决定询问是否有人可以向我解释在 angular2 项目中设置 WebSocket 的好方法。

我使用 angular2 + webpack 并在这个样板 https://github.com/angular/angular2-seed 上构建了我的项目

【问题讨论】:

    标签: javascript websocket angular


    【解决方案1】:

    如您所见

    https://github.com/afrad/angular2-websocket/blob/master/src/angular2-websocket.ts

    其他参数可选

    constructor(private url:string, private protocols?:Array<string>, private config?: WebSocketConfig  ) {
    

    你可能也喜欢它有工作套接字角度示例(使用 socket.io)

    https://github.com/leonardohjines/auctionApp

    【讨论】:

    • 谢谢,我认为我的 IDE 在 ES6 功能方面存在一些问题,这就是显示错误的原因。
    【解决方案2】:

    我也可以为 angular2 中的 websockets 推荐这个实现: https://github.com/Sinthor/WSM

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 2016-09-24
      • 2012-06-13
      • 1970-01-01
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2021-07-20
      相关资源
      最近更新 更多