在我的 Angular 服务中使用一次后如何重用 Promise<void>?

How to reuse Promise<void> after using it once in my Angular service?

我的 Angular Promise<void> 在我的一项服务中遇到问题。

服务与服务器的集线器建立 SignalR 连接。我正在等待广播到集线器以建立连接:

export class SignalRService {
  private hubConnection: signalR.HubConnection;
  private url = environment.apiUrl + 'messageHub';
  private thenable: Promise<void>;

public startConnection = (): void => {
    if (!this.hubConnection) {
      const token = this.auth.getAuth().token;
      this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl(this.url, { accessTokenFactory: () => token })
        .build();
      this.startHubConnection();

      this.hubConnection.onclose(() => this.connectionHubClosed());
    }
  };

private startHubConnection() {
    this.thenable = this.hubConnection.start();
    this.thenable
      .then(() => console.log('Connection started!'))
      .catch((err) => console.log('Error while establishing connection :('));
  }

public broadcastGameState = (): void => {
    this.thenable.then(() => {
      const name = this.auth.getAuth().displayName;
      let message = this.game.getGame();
      this.hubConnection
        .invoke('SendMessage', message)
        .catch((err) => console.error(err));
    });
  };

但之后我将关闭我的连接:

public stopConnection = (): void => {
    if (this.hubConnection) {
      this.hubConnection.stop();
    }
  };

再次使用我的服务,我不能再使用我的thenable,并且broadcastGameState不再等待它,抛出错误:

Error: Cannot send data if the connection is not in the 'Connected' State.

我不明白为什么?

xxh你说到点子上了,让我思考一下,所以我找到了问题:) 调用后:

public stopConnection = (): void => {
    if (this.hubConnection) {
      this.hubConnection.stop();
    }
  };

关闭连接时调用:

private connectionHubClosed(): void {
    //trigerred when lost connection with server
    alert('todo: SignalR connection closed');
  }

但 this.hubConnection 仍然具有分配的值,因此由于 if (!this.hubConnection) 新的 this.thenable 被跳过。