react-native - proxy.invoke 在反应本机信号器中无法在连接开始时工作
问题描述
我正在开发一个带有运行服务器react-native
的服务器的移动应用程序。以下是我里面的代码。到这里,服务器连接成功,里面的服务器方法在服务器上执行成功。asp.net
signalr
componentDidMount
.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
解决方案
您可以将调用移到 connection.start().done() 之外,但您需要禁用该按钮,直到建立连接之后。您可以在连接成功后启用该按钮。
就按钮而言,只需调用该按钮的单击事件并将您的调用放在该事件触发器中。
一个 jQuery 示例 -
$("#myButton").on("click", function (e) {
proxy = connection.createHubProxy("mobileStockTickerHub");
proxy.invoke("subscribeToSymbols", "123")
}
推荐阅读
- javascript - 字符串上的 indexOf 方法如何在 JavaScript 中工作
- flutter - Flutter:使用不包含 Navigator 的上下文请求的 Navigator 操作
- python - 当时区位于中间时,Python dateparser 失败
- java - 如何使用 java 自动登录 Citrix Netscaler 网关
- asp.net - 如何使用 c# 从标签之间的 XML 检索数据?
- jupyter - 无法判断
- sql - 如何为日常备份添加名称差异
- machine-learning - 使用 Keras 加快模型评估速度
- rust - 如何不将进度条数据与其他输出混合?
- node.js - 服务器发送的事件没有从 React 和 NodeJs 的流中接收消息