Angular: проблема с InjectableRxStompConfig - PullRequest
0 голосов
/ 14 апреля 2020

Я не эксперт, использующий Angular. Я пытаюсь работать с WebSockets, используя Spring Boot + Angular. Я нашел отличный учебник [https://blog.impulsebyingeniance.io/utilisation-des-websockets-sous-angular-avec-java-spring-boot/]

Git Репо: https://github.com/INGENIANCE/Websocket-With-Angular/tree/master/frontend

Когда я вытащил проект из git репозиторий, он работал отлично, и я протестировал его.

Но проблема в том, что когда я пытался интегрировать его в свой собственный проект, у меня была эта ошибка в websocket.service.ts [эта строка: this.stompService .stompClient.configure (this.stompConfig); ]: Типы свойств beforeConnect несовместимы. Тип '(клиент: RxStomp) => void | Обещание «нельзя назначить типу» () => void | Обещание

Каждый раз, когда я хочу интегрировать его в любой проект, он выдает мне эту ошибку.

Не могли бы вы помочь мне с этим?

Спасибо!

websocket.service.ts

import { InjectableRxStompConfig, RxStompService  } from '@stomp/ng2-stompjs';
import { Observable } from 'rxjs';
import { WebSocketOptions } from './models/websocket.options';
import { SocketResponse } from './models/websocket.response';
/**
 * A WebSocket service allowing subscription to a broker.
 */
export class WebSocketService {
  private obsStompConnection: Observable<any>;
  private subscribers: Array<any> = [];
  private subscriberIndex = 0;
  private stompConfig: InjectableRxStompConfig = {
    heartbeatIncoming: 0,
    heartbeatOutgoing: 20000,
    reconnectDelay: 10000,
    debug: (str) => { console.log(str); }
  };

  constructor(
    private stompService: RxStompService,
    private updatedStompConfig: InjectableRxStompConfig,
    private options: WebSocketOptions
    ) {
    // Update StompJs configuration.
    this.stompConfig = {...this.stompConfig, ...this.updatedStompConfig};
    // Initialise a list of possible subscribers.
    this.createObservableSocket();
    // Activate subscription to broker.
    this.connect();
  }

  private createObservableSocket = () => {
    this.obsStompConnection = new Observable(observer => {
      const subscriberIndex = this.subscriberIndex++;
      this.addToSubscribers({ index: subscriberIndex, observer });
      return () => {
        this.removeFromSubscribers(subscriberIndex);
      };
    });
  }

  private addToSubscribers = subscriber => {
    this.subscribers.push(subscriber);
  }

  private removeFromSubscribers = index => {
    for (let i = 0; i < this.subscribers.length; i++) {
      if (i === index) {
        this.subscribers.splice(i, 1);
        break;
      }
    }
  }

  /**
   * Connect and activate the client to the broker.
   */
  private connect = () => {
    this.stompService.stompClient.configure(this.stompConfig); //error is here
    this.stompService.stompClient.onConnect = this.onSocketConnect;
    this.stompService.stompClient.onStompError = this.onSocketError;
    this.stompService.stompClient.activate();
  }

  /**
   * On each connect / reconnect, we subscribe all broker clients.
   */
  private onSocketConnect = frame => {
    this.stompService.stompClient.subscribe(this.options.brokerEndpoint, this.socketListener);
  }

  private onSocketError = errorMsg => {
    console.log('Broker reported error: ' + errorMsg);

    const response: SocketResponse = {
      type: 'ERROR',
      message: errorMsg
    };

    this.subscribers.forEach(subscriber => {
      subscriber.observer.error(response);
    });
  }

  private socketListener = frame => {
    this.subscribers.forEach(subscriber => {
      subscriber.observer.next(this.getMessage(frame));
    });
  }

  private getMessage = data => {
    const response: SocketResponse = {
      type: 'SUCCESS',
      message: JSON.parse(data.body)
    };
    return response;
  }

  /**
   * Return an observable containing a subscribers list to the broker.
   */
  public getObservable = () => {
    return this.obsStompConnection;
  }
}
...