在Angular5中使用SockJS出现错误 - "sockjs_client_1.SockJS不是一个构造函数"

5

我目前正在按照这篇教程进行学习,现在我需要在我的Angular5组件中实例化SockJS客户端。

以下是我所做的:

  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);
                }
            });
        });
    }
    
我遇到的错误是:

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

我找不到任何关于这个问题的信息。
1个回答

10

尝试以下两种方法之一:

import * as SockJS from 'sockjs-client';
或者
import SockJS from 'sockjs-client';

第一个选项对我有用,非常感谢!!! 你能解释一下为什么我的选项会导致那个错误吗? - coolaturon
我只能说,这是我在另一个使用SockJS的示例中看到的导入方式。我想这只是模块定义的问题。 - kshetline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接