【问题标题】:Websocket creation using sockjs-client/sockjs in angular2 webapp project在 angular2 webapp 项目中使用 sockjs-client/sockjs 创建 Websocket
【发布时间】: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


    【解决方案1】:

    找到了一种在不使用typings 的情况下将 sockjs 集成到 angular2 中的方法。

    使用以下步骤:

    1. 在index.html 中导入sockjs-event.js 和sockjs-client.js
         <!doctype html>
         <html>
          <head>
          <meta charset="utf-8">
            <title>MyApp</title>
            <script src="/sockjs-client.js"></script>
            <script src="/sockjs-event.js"> </script> 
    
             ......
             </head>
             <body>
              <my-app>Loading...</my-app>
            </body>
         </html>
    
    1. 创建导出服务myapp.service.ts
        declare var EventBus: any;
        @Injectable()
         export class ConsoleService {
          URL: string = 'http://localhost:8082/eventbus';
          handlers = {};
          eventBus: any;
          private _opened: boolean = false;
    
           public open(): void {
    
           if (!this._opened) {
            this.eventBus = new EventBus(this.URL);
            this.eventBus.onopen = (e) => {
                   this._opened = true;
                    console.log("open connection");
                    this.callHandlers('open', e);
                    this.eventBus.publish("http://localhost:8082", "USER LOGIN                 INFO");
    
                    this.eventBus.registerHandler("http://localhost:8081/pushNotification", function (error, message) {
                       console.log(message.body);
    
    
                    //$("<div title='Basic dialog'>Test   message</div>").dialog();
    
              });
            }
            this.eventBus.onclose = (e) => {
                this.callHandlers('close', e);
              }
            }
        }
    
         public isOpen(): boolean {
          return this._opened;
         }
    
        public close(): void {
          if (this._opened) {
            this.eventBus.close();
            delete this.eventBus;
            this._opened = false;
         }
    
         }
    
          .......
    
    
    
        public send (type: string, data: any) {
            if (this._opened) {
                var msg = JSON.stringify({
                  type: type,
                 data: data
              });
    
              this.eventBus.publish("http://localhost:8082",msg);
            }
          }
        };
    
         export default ConsoleService;
    
    1. 转到您的起始模块,在我的例子中是app.module.ts,然后在角度引导程序中加载您的服务myapp.service.ts
          import { AppComponent } from './app.component';
          ....
          import { ConsoleService } from 'services/myapp.service';
    
            @NgModule({
              imports: [
                ....
              ],
            providers:    [ ConsoleService ],
    
          declarations: [
              AppComponent,
            ...
           ],
             bootstrap: [AppComponent]
         })
    

    4.从你的起始组件app.component.ts调用open websocket

          import { Component } from '@angular/core';
          import 'style/app.scss';
          import { ConsoleService } from 'services/globalConsole.service';
          @Component({
           selector: 'my-app', // <my-app></my-app>
           templateUrl: './app.component.html',
           styleUrls: ['./app.component.scss']
    
          })
    
        export class AppComponent {
    
          constructor (private consoleService: ConsoleService) {
            consoleService.onOpen((e) => {
                     consoleService.send('message', "xyz");
                 });
    
              consoleService.open();
           }
    
      }
    
    1. 最后,您可以使用 import ConsoleService 在任何 .ts 文件中使用 EventBus 到 publish 和 registerHandler。

    我希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 2015-07-24
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多