NgStomp 在 InjectableRxStompConfig 中使用 beforeConnect

NgStomp use beforeConnect in InjectableRxStompConfig

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

除了我需要在 connectHeaders 中设置我用来验证服务器端的令牌外,一切正常,为此我读到我需要使用函数 beforeConnect

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

我的 rxStompConfig:

导出 class 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();
}

有人可以帮我解决这个问题吗?

勾选这个

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

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