Error using SockJS in Angular5 – "sockjs_client_1.SockJS is not a constructor"

Issue

I am following this tutorial at the moment and I got to the point, where I have to instantiate my SockJS-Client inside my Angular5 Component.

Here is what I did in:

  1. I exectuted the following commands to install the required libraries:

    npm install stompjs
    npm install sockjs-client
    npm install jquery
    
  2. I imported the libraries to my component like so:

    import { Stomp } from 'stompjs';
    import { SockJS } from 'sockjs-client';
    import $ from 'jquery';
    
  3. Finally I tried to instantiate SockJS:

    constructor(){
        this.initializeWebSocketConnection();
    }
    
    initializeWebSocketConnection(){
        let ws = new SockJS(this.serverUrl);  //<- This is the line causing the error
        this.stompClient = Stomp.over(ws);
        let that = this;
        this.stompClient.connect({}, function(frame) {
            that.stompClient.subscribe("/chat", (message) => {
                if(message.body) {
                    $(".chat").append("<div class='message'>"+message.body+"</div>")
                    console.log(message.body);
                }
            });
        });
    }
    

The error I am getting is:

ERROR Error: Uncaught (in promise): TypeError: sockjs_client_1.SockJS is not a constructor

I can’t find anything about this problem.

Solution

Try either:

import * as SockJS from 'sockjs-client';

or

import SockJS from 'sockjs-client';

Answered By – kshetline

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.