SignalR 错误类型错误:无法读取未定义的属性“订阅”

时间:2021-04-27 13:11:40

标签: angular signalr

我想订阅但没有工作。

检查我的代码:

服务:

在 ts:

 test() { return test }

在订阅中我看到:

Property 'subscribe' does not exist on type 'void'.ts(2339)

什么问题?

2 个答案:

答案 0 :(得分:1)

您可以调整代码,以便将数据推送到可观察对象。然后你可以订阅在任何地方阅读:

服务:

hubMessage$ = new BehaviorSubject({});

public startConnection = () => {
    let token: any = JSON.parse(localStorage.getItem("token") || '{}');
    this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('https://api/endpoint',
            { accessTokenFactory: () => token}) 
        .build();


    this.hubConnection
        .start()
        .then(() => console.log('Connection started'))
        .catch(err => { console.log('Error while starting connection: ' + err) }) 

    this.hubConnection.on('message', (data) => { 
      this.hubMessage$.next(data);
    });
   
}

在 ts:

 private startHttpRequest = () => { 
    this.signalRService.hubMessage$.subscribe(
      (data: any) => console.log(data)
    )
 }

答案 1 :(得分:0)

您可以使用@eko 的方法,也可以使用这样的回调函数:

服务

public addTransferChartDataListener = (callbackFn) => {
   return this.hubConnection.on('message', callbackFn);
} 

组件

private startHttpRequest = () => { 
    this.signalRService.addTransferChartDataListener((data: any) => console.log(data));
}