我在其中一个 Controller 中有以下方法。当我使用 {{ getLastMessage }}
从 html 代码调用此方法时,浏览器崩溃。多次调用该方法,浏览器无响应。有人可以帮忙解决这个问题吗?
$scope.getLastMessage = function(userId) {
var query = {};
query['uid'] = userId;
var lastMessage = $meteor.collection(function(){
return Chats.find(query, {fields: {'_id':1, 'content':1, 'uid':1}});
});
console.log(lastMessage);
return lastMessage;
};
最佳答案
我认为你的问题是 getLastMessage
是一个函数,而不是一个属性,所以你的代码相当于 {{ function(){} }}
甚至从未被调用。您需要实际调用 {{getLastMessage()}}
等函数,或立即调用 Controller 上的函数。
如果我可以为您提供一个稍微简单的解决方案(尽管可能效率较低):
如果您尚未将集合绑定(bind)到范围变量,您可能需要执行以下操作:
// SERVER CODE -- put in your /server directory
// NB: I am only publishing the specific user's (uid) chats in case someone
// finds this through Google and by accident creates a vulnerability
// unintentionally. Feel free to change the Mongo query if you want to
// publish all chats to all users
Meteor.publish("Chats", function () {
return Chats.find({uid:this.userId}, {fields: {'_id': 1,'content': 1,'uid': 1}});
});
// CLIENT CODE
$scope.chatsCollection = $scope.$meteorCollection("Chats").subscribe("Chats");
// lastMessage should be updated reacitvely -- no need to run a function
$scope.lastMessage = $scope.chatsCollection.slice(-1)[0];
话虽如此,slice 假设 Meteor Collection 正在按时间顺序将新文档附加到末尾,因此实际情况可能不会那么简单。 $scope.chatsCollection 具有数组的所有方法,因此您可以对其进行排序或使用 underscore.js 之类的东西对其进行查询。
您可能考虑采取的另一种方法是使用纯 Meteor Cursor.observe
method ——看起来你在最初的方法中遵循了这一点。这里的一个好处是您可以对 Mongo 查询执行任何必要的排序操作,这可能会更有效。
我认为这看起来像:
// CLIENT SIDE CODE
// Initial assignment
$scope.lastMessage = Chats.find({uid:Meteor.userId(), {
fields: {
'_id': 1,
'content': 1,
'uid': 1
},
sort: {INSERT YOUR SORT HERE, e.g. by creation time}
})
.fetch().slice(-1).pop();
// Subscription to changes made on the query
Chats.find({uid:Meteor.userId(), {
fields: {
'_id': 1,
'content': 1,
'uid': 1
},
sort: {INSERT YOUR SORT HERE, e.g. by creation time}
})
.observe({added: function(document){$scope.lastMessage = document}});
关于javascript - meteor :应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32358843/