2

我正在尝试构建一个使用 websockets 的角度客户端,并且我正在使用 @stomp/ng2-stompjs 我正在遵循本指南https://stomp-js.github.io/guide/ng2-stompjs/ng2-stomp-with -angular7.html

除了我需要在 connectHeaders 中设置用于验证服务器端的令牌之外,一切都运行良好,为此我读到我需要使用 beforeConnect 函数

我尝试了各种方式,但我不明白如何使用它,它卡住或发送一个空令牌

我的 rxStompConfig:

导出类 RxStompConfig 扩展 InjectableRxStompConfig {

constructor(private userService: UserService) {
    super();
    this.brokerURL = env.wsServerBaseUrl;

    // Interval in milliseconds, set to 0 to disable
    this.heartbeatIncoming = 0; // Typical value 0 - disabled
    this.heartbeatOutgoing = 20000; // Typical value 20000 - every 20 seconds

    // Wait in milliseconds before attempting auto reconnect
    // Set to 0 to disable
    // Typical value 500 (500 milli seconds)
    this.reconnectDelay = 5000;
    // Will log diagnostics on console
    // It can be quite verbose, not recommended in production
    // Skip this key to stop logging to console
    this.debug = (msg: string): void => {
        console.log(new Date(), msg);
    };
    console.log('Constructor ' + this.connectHeaders);

    this.beforeConnect = (): Promise<void> => {
        return new Promise<void>((resolve, reject) => {
            this.userService.currentToken.subscribe(token => {
                console.log('Subscribed');
                if (token) {
                    console.log('Resolved ' + token);
                    this.connectHeaders = { Authorization: `Bearer ${token}`};
                    resolve();
                }
            });
        });
    };
}

我从进行身份验证并设置令牌的服务中获取令牌

这是 currentToken 方法:

get currentToken(): Observable<string> {
    return this.$token.asObservable();
}

有人可以帮我吗?

4

1 回答 1

1

检查这个

https://github.com/stomp-js/rx-stomp/issues/204

有一个修复程序可以解决您的问题。基本上现在在 beforeConnect 中,您可以接收可以配置的 stompClient,在您的特定情况下,您将能够设置 connectHeaders

于 2020-04-05T11:44:29.383 回答