angularwebsocketpromisestompstompjs

NgStomp use beforeConnect in InjectableRxStompConfig


I am trying to build a angular client that uses websockets, and I am using @stomp/ng2-stompjs I am following this guide https://stomp-js.github.io/guide/ng2-stompjs/ng2-stomp-with-angular7.html

Everything works perfectly except that I need to set in the connectHeaders the token that I use to authenticate server side, to do this I read that I need to use the function beforeConnect

I tried in various way but I don't understand how to use it, it gets stuck or it sends a empty token

My rxStompConfig:

export class RxStompConfig extends 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();
                }
            });
        });
    };
}

I take the token from a service that does the authentication and sets the token

This is currentToken method:

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

Can someone help me on this?


Solution

  • Check this one

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

    There was a fix that should solve your issue. Basically now in the beforeConnect you can receive the stompClient that can be configured and in your particular case you will be able to set the connectHeaders