【问题标题】:SignalR ERROR TypeError: Cannot read property 'subscribe' of undefinedSignalR 错误类型错误:无法读取未定义的属性“订阅”
【发布时间】:2021-05-05 15:44:24
【问题描述】:

我想订阅但没有工作。

检查我的代码:

服务:

在ts中:

 test() { return test }

在订阅我看到:

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

什么问题?

【问题讨论】:

  • 似乎this.hubConnection.on 没有返回任何内容。实际上,回调在on 参数内,它不会返回 Observable...
  • 我同意,但是如何解决这个问题

标签: angular signalr


【解决方案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)
    )
 }

【讨论】:

  • 我没有收到消息。我只在网络中看到 { type":6 } {"type":6} {"type":6} {"type":6}
  • 这是什么消息类型:6?
  • 如果hubConnection.on("message")事件正在执行,那么它将把数据推送到hubMessage$主题。然后你就可以订阅它了。如果“消息”事件没有发送任何内容,那么您将看不到任何内容。你确定this.hubConnection.on('message') 有效吗?
  • 我不确定。我什至不知道如何测试。只有在第一个 api 连接上,我才会定期收到消息 {type: 6}?在控制台中,我看到消息“连接已启动”,仅此而已
  • 这也是ibb.co/7rvcCdM 这是我所有的ws网络
【解决方案2】:

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

服务

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

组件

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

【讨论】:

  • 我没有收到消息。我只在网络中看到 { type":6 } {"type":6} {"type":6} {"type":6}
  • 这是什么消息类型:6?
  • 我建议你阅读SignalR 文档。并遵循一些准则,您接收的type: 6SignalR 交换以保持连接活动的默认消息。请先阅读,然后尝试询问...
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多