【发布时间】:2017-11-12 13:24:34
【问题描述】:
我正在使用 Angular2 和 Meteor。由于我在客户端添加了该代码,因此我的 Chrome 控制台中有一个异常(超出了最大调用堆栈大小):
var userChannelsId = UserChannels.find({idUser: Meteor.userId()});
this.channels = Channels.find({_id: {$in: userChannelsId}});
据我发现,当存在无限循环时会发生此异常。我确定错误来自这一行(我调试了我的代码,直到我确定为止)。 问题是否出在第二次开始时第一次搜索没有完成?
所有功能:
getChannelList(): void {
console.log('ok');
var userChannelsId = UserChannels.find({idUser: Meteor.userId()});
this.channels = Channels.find({_id: {$in: userChannelsId}});
console.log('ko');
this.channels.subscribe(channel => {
this.selectChannel(channel[0]);
});
}
编辑:
作为@MichaelSolati,我试图只获取 userChannel 的 IdChannel,但我仍然有同样的错误......它返回一个 observable 而不是一个数组。也许是问题所在?这就是我所做的:
getChannelList(): void {
console.log('ok');
let userId = Meteor.userId();
var userChannelsId = UserChannels.find({idUser: userId});
var values = userChannelsId.map((userChannels:Array<UserChannel>) => {
let result:Array<String> = [];
if (userChannels) {
userChannels.forEach((userChan) => {
result.push(userChan.idChannel);
});
}
return result;
});
this.channels = Channels.find({_id: {$in: values}});
console.log('ko');
this.channels.subscribe(channel => { this.selectChannel(channel[0]); });
}
【问题讨论】:
-
使用
setTimeout(function() { // your code here },0})避免调用堆栈大小超出问题 -
我必须在函数中添加什么?我所有的 getChannelList 代码,还是只是我的 Collection.find ?
-
你必须把你的无限代码放在
setTimeout回调函数中 -
问题是异常触发了超时,我的代码没有执行……所以我认为setTimeout只是避免了问题,并没有解决问题:(
-
最佳实践是不订阅助手。助手被一遍又一遍地调用,而且可能以你意想不到的方式调用,所以那里的任何操作都应该是幂等的。我通常在 onCreated() 函数中处理我的所有订阅。
标签: javascript mongodb angular meteor