尝试在Angular2中使用stomp.js

4
我正在尝试使用stomp.js实现Stomp Websocket客户端。我正在使用angular2、typescript和webpack,对这些技术都很陌生。我的angular2项目是基于此种子构建的: https://github.com/angular/angular2-seed。 我使用https://github.com/sjmf/ng2-stompjs-demo作为实现stomp.js客户端的指南。 我目前遇到的错误如下:
?d41d:73 EXCEPTION: TypeError: Cannot read property 'client' of undefined in [null]

错误发生在这个方法中:
  public configure() : void {

    // Check for errors
    if (this.state.getValue() != STOMPState.CLOSED) {
      throw Error("Already running!");
    }

    let scheme : string = 'ws';
    if( AppSettings.IS_SSL ) {
      scheme = 'wss';
    }

    this.client = Stomp.client(
      scheme + '://'
      + AppSettings.HOST + ':'
      + AppSettings.WEBSOCK_PORT
      + AppSettings.WEBSOCK_ENDPOINT
    );

    this.client.heartbeat.incoming = AppSettings.HEARTBEAT;
  }

所以,Stomp 似乎未定义。

我正在导入:

import {Stomp} from "stompjs";

我已经按照以下的方式使用npm安装了stomp.js:

npm install --save stompjs

我的stompjs模块如下所示:
declare module "stompjs" {

  export interface Client {
    heartbeat: any;

    debug(...args: string[]);

    connect(...args: any[]);
    disconnect(disconnectCallback: () => any, headers?: any);

    send(destination: string, headers?:any, body?: string);
    subscribe(destination: string, callback?: (message: Message) => any, body?: string);
    unsubscribe();

    begin(transaction: string);
    commit(transaction: string);
    abort(transaction: string);

    ack(messageID: string, subscription: string, headers?: any);
    nack(messageID: string, subscription: string, headers?: any);
  }

  export interface Message {
    command: string;
    headers: any;
    body: string;

    ack(headers?: any);
    nack(headers?: any);
  }

  export interface Frame {
    constructor(command: string, headers?: any, body?: string);

    toString(): string;
    sizeOfUTF8(s: string);
    unmarshall(datas: any);
    marshall(command: string, headers?, body?);
  }

  export interface Stomp {
    client: Client;
    Frame: Frame;

    over(ws: WebSocket);
  }
}

我觉得我的模块和实际的库之间缺少连接,但我不知道如何做到这一点,也无法从github演示中弄清楚。

非常感谢您提前的任何帮助!


1
我不确定你最终是否解决了这个问题,但我认为这是一个bug。其他人在repo上提出了一个问题,我能够修复对Stomp变量的缺失引用。https://github.com/sjmf/ng2-stompjs-demo/issues/1 - Sam Finnigan
如果我没记错的话,我成功地让它工作了,而没有使用类型。感谢您的建议。 - Jakob Abfalter
一个演示项目可以在 https://github.com/sjmf/ng2-stompjs-demo 找到。 - Jimi
2个回答

1
你是否尝试在接口之外也导出了一个变量?
export var Stomp: Stomp;

0

在Angular2(或Angular4)中直接使用Stomp.js绝对不是一件容易的事情。

如果需要一个适用于Angular2(和Angular4)类型的StompService,可以使用Observables,请参考https://github.com/stomp-js/ng2-stompjs

同时还提供了Angular2和Agular4的示例应用程序。


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