我对Electron很新,目前正在构建一个小应用程序,它重用了我之前构建的Angular应用程序中的一些代码。
以下是我要做的事情:我有一个主要的BrowserWindow(正在填充来自webservice的数据,我使用angular访问),当用户点击其中一个按钮我要打开另一个BrowserWindow并显示其中包含一些数据(数据与用户点击的内容有关)。我想出了如何打开另一个BrowserWindow以及如何传递一些参数,请参阅下面的代码示例。
当用户点击按钮时,正在执行此代码,新的BrowserWindow将打开。
const BrowserWindow = remote.BrowserWindow;
var cubeWindow = new BrowserWindow({ width: 800, height: 600, frame: false });
var cube = path.resolve(__dirname, '../cube.html');
cubeWindow.loadURL(cube);
var data = {
id: "1",
name: "this"
};
cubeWindow.webContents.on('did-finish-load', ()=> {
cubeWindow.webContents.send('cube-data', data);
})

在这里,我访问刚刚打开的BrowserWindow中的数据(这个javascript文件在cube.html中引用):
require('electron').ipcRenderer.on('cube-data', (event, message) => {
console.log(message);
});

数据对象的内容正在新的BrowserWindow中记录,到目前为止一直很好。现在问我的问题:如何访问在cube.html中运行的Angular应用/控制器中的数据对象?
我尝试这样做,但这不起作用:
var data;
require('electron').ipcRenderer.on('cube-data', (event, message) => {
console.log(message);
data = message;
});
angular.module('testApp', [])
.controller('appCtrl', function($scope) {
$scope.data = data;
console.log('Data: ' + $scope.data);
});

Angular控制器的日志条目表示数据未定义,我认为是因为在ipcRenderer发送/接收消息之前实际评估了控制器?
有没有办法在Angular中访问已发送的消息?
答案 0 :(得分:1)
尝试将cube-data
事件处理程序放在控制器代码中:
angular.module('testApp', [])
.controller('appCtrl', function($scope) {
$scope.model = {
data: null
}
function attachCubeDataHandler() {
require('electron').ipcRenderer.on('cube-data', (event, message) => {
console.log(message);
$scope.model.data = message;
});
}
function initialize() {
attachCubeDataHandler();
}
// Invoke initialization
initialize();
});
这样,您首先初始化控制器,然后解析事件响应。此外,如果您将代码放在控制器中,您可以直接使用$scope
来更新视图的数据。我将data
与另一个对象(model
)打包在一起,以确保在data
对象更改时视图更新。
答案 1 :(得分:1)
好的我明白了:基于atom.io上的 jdfwarrior 的post,我们必须使用一点Angular $ timeout hack来使事情有效。在我将PJDev提供的代码片段更改为以下内容后,它工作正常。它现在记录消息的内容,并在视图(cube.html)中显示它。
angular.module('testApp', [])
.controller('appCtrl', ['$timeout', '$scope', function($timeout, $scope) {
$scope.model = {
data: null
}
function attachCubeDataHandler() {
require('electron').ipcRenderer.on('cube-data', (event, message) => {
$timeout(function() {
$scope.model.data = message;
console.log("in timeout: " + message);
},0);
});
}
function initialize() {
attachCubeDataHandler();
}
// Invoke initialization
initialize();
});