首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在angular2 webapp项目中使用sockjs-client/sockjs创建Websocket

在angular2 webapp项目中使用sockjs-client/sockjs创建Websocket
EN

Stack Overflow用户
提问于 2016-12-18 12:25:10
回答 1查看 2.9K关注 0票数 1

我在前端使用Angular2 webapp项目,后端使用Vertex3。

使用Sockjs,我正在创建websocket (在客户端),以便在前端和后端之间创建一个通信通道。

我已经使用npm安装了sockjs-客户端:

npm安装sockjs-client

当我在LoginService.ts文件中导入sockjs时:

从‘’导入*作为SockJS;

代码语言:javascript
复制
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客户端,因此无法创建websocket连接。

2.将angular2 webapp项目构建为“sockjs”时,在node_modules中找不到错误(奇怪的是,它存在于node_modules中)

我遗漏了什么吗?

提前谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-22 15:13:24

找到了一种在angular2中集成套接字而不使用typings的方法。

使用以下步骤:

  1. 导入sockjs-event.jssockjs-client.js中的index.html
代码语言:javascript
复制
     <!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
代码语言:javascript
复制
    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
代码语言:javascript
复制
      import { AppComponent } from './app.component';
      ....
      import { ConsoleService } from 'services/myapp.service';

        @NgModule({
          imports: [
            ....
          ],
        providers:    [ ConsoleService ],

      declarations: [
          AppComponent,
        ...
       ],
         bootstrap: [AppComponent]
     })

4.从起始组件app.component.ts调用打开的websocket

代码语言:javascript
复制
      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. 最后,您可以使用导入EventBus在任何.ts文件中使用ConsoleServiceregisterHandler

我希望这会有所帮助:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41208297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档