我是Electron的新手,我坚持如何将请求结果传递给视图。
这是js文件:
const request = require('request');
let serverUrl = 'http://localhost:3000/api';
request.get({
url: serverUrl + '/properties'
}, handleResponse);
var properties = {};
function handleResponse(error, response, body) {
properties = JSON.parse(response.body);
console.log(properties);
}
这是html部分:
<div class="block">
<div class="title">General</div>
<script>
const { remote } = require('electron');
console.log(properties);
for (var i in remote.properties) {
document.write('<p>' + remote.properties[i] + '</p>');
}
</script>
我知道请求是异步的,这就是为什么视图中的console.log(properties)
打印{}
的原因。那么有什么方法可以将请求结果发送到视图?
答案 0 :(得分:3)
您可以调度来自渲染器进程的请求并在接收到数据后在回调中处理响应,也可以在主进程中发出请求,然后将消息发送给渲染器。
<!DOCTYPE html>
<html>
<body>
</body>
<script type="text/javascript">
const request = require('request')
let serverUrl = 'http://localhost:3000/api'
request.get({
url: serverUrl + '/properties'
}, handleResponse)
function handleResponse(error, response, body) {
properties = JSON.parse(response.body)
for (var i in properties) {
document.write('<p>' + properties[i] + '</p>')
}
}
</script>
</html>
主要:
const request = require('request')
let serverUrl = 'http://localhost:3000/api'
request.get({
url: serverUrl + '/properties'
}, handleResponse)
function handleResponse(error, response, body) {
properties = JSON.parse(response.body)
mainWindow.webContents.send('my_message', properties)
}
渲染器:
<!DOCTYPE html>
<html>
<body>
</body>
<script type="text/javascript">
require('electron').ipcRenderer.on('my_message', function(e, message) {
console.log(message)
for (var i in message) {
document.write('<p>' + message[i] + '</p>');
}
});
</script>
</html>
答案 1 :(得分:0)
我终于找到了解决方案,方法是将请求封装在带有回调的函数中,如下所示:
function getProperties(callback) {
request.get({
url: serverUrl + '/properties'
}, function (error, response, body) {
callback(JSON.parse(response.body));
});
}
现在从视图中,我只需要调用getProperties
:
<div class="block">
<div class="title">General</div>
<script>
getProperties((properties) => {
console.log(properties);
});
</script>
</div>