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

前端之家收集整理的这篇文章主要介绍了在angular2 webapp项目中使用sockjs-client / sockjs创建Websocket前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Angular2 webapp项目用于FRONT-END而Vertex3用于BACK-END.

使用Sockjs-client我正在创建websocket(在客户端)以在前端和后端之间创建通信通道.

我使用npm安装了sockjs-client:

npm install sockjs-client

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

import * as SockJS from ‘sockjs-client’;

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 run server

但是在客户端没有创建websocket连接.因为我已经使用vertex vertex.createHttpServer(托管于:http://localhost:8082)创建了服务器.

所以我有两个问题:

1.无法在angular2 webapp中导入sockjs-client,因此无法创建websocket连接.

2.在node_modules中找不到构建angular2 webapp项目时出错’sockjs-client'(奇怪的是它存在于node_modules中)

有什么我想念的吗?

提前致谢 !!!

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

使用以下步骤:

  1. Import sockjs-event.js and sockjs-client.js in index.html
<!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. Create an export Service 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. Go to your starting module in my case it is app.module.ts and load your service myapp.service.ts in angular bootstrap
import { AppComponent } from './app.component';
      ....
      import { ConsoleService } from 'services/myapp.service';

        @NgModule({
          imports: [
            ....
          ],providers:    [ ConsoleService ],declarations: [
          AppComponent,...
       ],bootstrap: [AppComponent]
     })

4.Call open websocket from your starting component app.component.ts

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. Finally you can use EventBus to publish and registerHandler in any .ts file using import ConsoleService .

我希望这个能帮上忙 :)

猜你在找的Angularjs相关文章