我正在编写一个带有node.js前端的电子( AngularJS )应用程序。由于node.js运行在OS级别,而角度运行在客户端级别,两者使用IPC (或者在本例中是由https://github.com/develephant/electangular实现的ipc )相互交谈。
在这种情况下,我有一个用于向节点应用程序发送IPC消息的服务:
app.service('msgService', ['ipc', '$rootScope', '$q', function(ipc, $rootScope, $q){
this.sendMsg = function(type, value) {
var message = {
type: type,
value: value
};
ipc.send(message);
};
}]);此服务被注入主控制器,并由主控制器调用:
app.controller('mainController', ['$scope', '$rootScope', 'electron', 'msgService', 'hey', function($scope, $rootScope, electron, msgService, hey){
msgService.sendMsg('db_find', {});
// I can see the variable inside this console.log
console.log($rootScope);
// I get undefined here
console.log($rootScope.msg);
}]);一旦节点应用程序生成了请求,它就通过ipc发送回一条消息,然后通过角应用程序的.run部分中的一段代码获取消息:
app.run(['$window', '$rootScope', function($window, $rootScope) {
$rootScope.$on('electron-msg', (event, msg) => {
$rootScope.msg = msg;
});
}]);上面简单地设置了运行中的$rootScope变量的msg属性,然后我希望能够从控制器内部访问该属性。您可以从console.log行的注释中注意到,我可以访问$rootScope并返回值,但是当我尝试并单独记录$rootScope.msg时,我会得到“未定义”。在尝试从$rootScope.msg变量中设置变量时,这也是正确的--我没有定义。
我已经试过所有的方法了,而且我已经筋疲力尽了!
(任何值得赞赏的帮助:)
编辑:
以下是console.log($rootScope)的输出;根据请求:
Scope {$id: 1, $$childTail: ChildScope, $$childHead: ChildScope, $$prevSibling: null, $$nextSibling: null…}
$$ChildScope
:
ChildScope()
$$applyAsyncQueue
:
Array[0]
$$asyncQueue
:
Array[0]
$$childHead
:
Scope
$$childTail
:
Scope
$$destroyed
:
false
$$isolateBindings
:
null
$$listenerCount
:
Object
$$listeners
:
Object
$$nextSibling
:
null
$$phase
:
null
$$postDigestQueue
:
Array[0]
$$prevSibling
:
null
$$watchers
:
Array[2]
$$watchersCount
:
99
$id
:
1
$parent
:
null
$root
:
Scope
msg
:
Array[4]
notificationCount
:
0
notifications
:
Array[0]
online
:
true
__proto__
:
Object为错误的格式表示歉意!但是你可以看到msg坐在$rootScope里面!
发布于 2016-09-21 12:33:17
电子库似乎是异步触发这些消息的,这会导致在日志记录时还没有填充$rootScope.msg。
当然,您只需在您的控制器中收听该事件:
msgService.sendMsg('db_find', {});
$rootScope.$on("electron-msg", (event, msg) => {
// message done
console.log(msg);
});当然,这也会捕获通过ipc服务发送的任何其他消息。
发布于 2016-09-21 12:34:57
正如注释中所讨论的,@Adam在尝试console.log之后调用异步函数时遇到了问题。为了确保他在函数执行后使用他想要的数据,下面的代码适用于他。
angular.element(document).ready(function () {
console.log('Hello World');
});希望它也能帮助别人
https://stackoverflow.com/questions/39616155
复制相似问题