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



我的一个服务中的AngularPromise<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();
}
};

然后再次使用我的服务,我不能再使用我的thenablebroadcastGameState也不再等待它,抛出一个错误:

错误:如果连接不在"Connected"中,则无法发送数据状态

我不明白为什么?

xxh你明白了你的意思,让我思考,所以我发现了问题:(在调用:后

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

连接关闭时称为:

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

但是这个.hubConnection仍然有赋值,所以由于if (!this.hubConnection),新的this.thenable被跳过。

最新更新