我在其中一个控制器中有以下方法。当我使用{{ 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;
};发布于 2015-09-04 05:41:36
我认为你的问题是getLastMessage是一个函数,而不是一个属性,所以你的代码等同于{{ function(){} }},甚至从来没有被调用过。您需要实际调用像{{getLastMessage()}}这样的函数,或者立即调用控制器上的函数。
如果我可以提供一个稍微简单一点的解决方案(尽管效率可能较低):
如果您还没有将集合绑定到作用域变量,那么您可能希望执行以下操作:
// 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];也就是说,切片假设Meteor Collection按照时间顺序将新文档添加到末尾,因此实际情况可能并不那么简单。$scope.chatsCollection具有数组的所有方法,因此您可以对其进行排序或使用underscore.js之类的东西对其执行查询。
您可以考虑采用的另一种方法是使用纯流星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}});https://stackoverflow.com/questions/32358843
复制相似问题