Websocket creation using sockjs-client/sockjs in angular2 webapp project

3.3k views Asked by At

I'm using Angular2 webapp project for FRONT-END and Vertex3 for BACK-END.

Using Sockjs-client i'm creating websocket (at client side) to create a communication channel between Frontend and Backend.

I have installed sockjs-client using npm :

npm install sockjs-client

When I import sockjs-client in LoginService.ts file :

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);
    }
}


}

no errors while running angular2 webapp project using

npm run server

But no websocket connection is created at client side. As I have already created server using vertex vertex.createHttpServer ( which is hosted on : http://localhost:8082).

So I have two issues :

1.Unable to import sockjs-client in angular2 webapp , so can't create websocket connection.

2.Error while building an angular2 webapp project as 'sockjs-client' is not found in node_modules (weird is that its present in node_modules )

Is there anything I'm missing ?

Thanks in Advance !!!

1

There are 1 answers

0
Shasha On BEST ANSWER

Found a way to integrate sockjs in angular2 without using typings.

Use Following steps:

  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 .

I hope this will help :)