首页 > 解决方案 > proxy.invoke 在反应本机信号器中无法在连接开始时工作

问题描述

我正在开发一个带有运行服务器react-native的服务器的移动应用程序。以下是我里面的代码。到这里,服务器连接成功,里面的服务器方法在服务器上执行成功。asp.netsignalrcomponentDidMount.start().done()

const connection = signalr.hubConnection(url);
//connection.logging = true;
proxy = connection.createHubProxy("mobileStockTickerHub");
proxy.on("msgreceived", (msg) => {
  //Alert.alert("Hi", "Message:" + msg);
  this.setState({ randomdata: msg });
  //console.log(this.state.randomdata);
});

// attempt connection, and handle errors
connection
  .start()
  .done(() => {
    console.log("Now connected, connection ID=" + connection.id);

    proxy
      .invoke("setUserName", "Hemal")
      .done((directResponse) => {
        console.log("direct-response-from-server", directResponse);
      })
      .fail(() => {
        console.warn(
          "Something went wrong when calling server, it might not be up and running?"
        );
      });
    proxy.invoke("subscribeToSymbols", "123");//THIS METHOD I NEED TO CALL FROM SOMEWHERE ELSE IN THE PAGE, NOT HERE IMMEDIATELY AFTER CONNECTION MADE
  })
  .fail(() => {
    console.log("Failed");
  });

//connection-handling
connection.connectionSlow(() => {
  console.log(
    "We are currently experiencing difficulties with the connection."
  );
});

connection.error((error) => {
  const errorMessage = error.message;
  let detailedError = "";
  if (error.source && error.source._response) {
    detailedError = error.source._response;
  }
  if (
    detailedError ===
    "An SSL error has occurred and a secure connection to the server cannot be made."
  ) {
    console.log(
      "When using react-native-signalr on ios with http remember to enable http in App Transport Security https://github.com/olofd/react-native-signalr/issues/14"
    );
  }
  console.debug("SignalR error: " + errorMessage, detailedError);
});

在 connection.start().done() 内部调用的方法有效,这个proxy.invoke("subscribeToSymbols", "123"),但是如果我想在服务器上执行一些方法,而不是在立即连接之后,而是稍后单击某个按钮时。

通过单击按钮执行此调用调用时,显示以下错误。

Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.

我正在使用这个 npm 信号器包进行本机反应,https://github.com/olofd/react-native-signalr

标签: react-nativesignalr

解决方案


您可以将调用移到 connection.start().done() 之外,但您需要禁用该按钮,直到建立连接之后。您可以在连接成功后启用该按钮。

就按钮而言,只需调用该按钮的单击事件并将您的调用放在该事件触发器中。

一个 jQuery 示例 -

$("#myButton").on("click", function (e) { 
    proxy = connection.createHubProxy("mobileStockTickerHub");
    proxy.invoke("subscribeToSymbols", "123")
}

推荐阅读