我花了一个半小时试图弄清楚这里有什么问题,我没有运气。非常感谢一些帮助,提前谢谢!
我的问题似乎是在下面的sendMailing()meteor方法中的“Roles.getUsersInRole(mailingAttributes.role).forEach”循环中,由客户端调用传递的变量“mailingAttributes”以某种方式存在覆盖,等第二次运行forEach()循环,没有.replace()替换
1 - 以下是发送到sendMailing()meteor方法的对象示例,以及第一次运行forEach()循环时它的显示方式
{
role: "admin", //Which user group to send the email to
subject: "Hello [[firstName]]!", //Email subject
html: "<h1>Hello [[firstName]] [[lastName]], how do you do?</h1>", //HTML Email
text: "Hello [[firstName]] [[lastName]], how do you do?" //Plain Text Email
}
2 - 现在forEach()传递用户对象,并用用户属性(名字和姓氏)替换这些占位符
3 - 鉴于用户Bob Jones,这里是第二次运行forEach()循环时同一对象出现的示例
{
role: "admin", //Which user group to send the email to
subject: "Hello Bob!", //Email subject
html: "<h1>Hello Bob Jones, how do you do?</h1>", //HTML Email
text: "Hello Bob Jones, how do you do?" //Plain Text Email
}
所以.replaces()没有改变...但是我永远不会改变应该存储这个对象的变量(mailingAttributes)......所以示例1和2之间应该没有区别
这是我的实际代码:
function sendMailingEmail(mailingAttributes) {
//Send email
Email.send({
from: 'no-reply@test.com',
to: mailingAttributes.to,
subject: mailingAttributes.subject,
html: mailingAttributes.html,
text: mailingAttributes.text,
});
}
//Set up rate limiting on the email send function
var sendMail = rateLimit(sendMailingEmail, 75); // wait at least 75 milliseconds between calls (1 second / 14 emails)
Meteor.methods({
sendMailing: function(mailingAttributes) {
//Check incoming attributes
check(mailingAttributes, {
role: String,
subject: String,
html: String,
text: String
});
// Confirm the user is logged in
if (this.userId === null || !Roles.userIsInRole(this.userId, 'admin'))
throw new Meteor.Error(401, 'You must be logged in and authorized');
Roles.getUsersInRole(mailingAttributes.role).forEach(function(userObject) {
//Create a temporary copy of the passed attributes
var userMailingAttributes = mailingAttributes;
//Make sure the user is subscribed to mailings
if (userObject.profile.subscribed === true) {
//Replace placeholders in text with user profile information
userMailingAttributes.subject = userMailingAttributes.subject.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.text = userMailingAttributes.text.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.html = userMailingAttributes.html.replace("[[firstName]]", userObject.profile.firstName).replace("[[lastName]]", userObject.profile.lastName);
userMailingAttributes.to = userObject.emails[0].address;
//Call the rate limited function, passing along the temporary copy of passed attributes (edited above)
sendMail(userMailingAttributes);
}
});
}
});
我正在使用alanning:roles&amp; dandv:限价套餐
答案 0 :(得分:1)
问题在于:
//Create a temporary copy of the passed attributes
var userMailingAttributes = mailingAttributes;
没有创建传递属性的临时副本 - 它正在创建指向内存中相同位置的新引用。如果改变那个,你就会改变另一个。
您要做的是clone the object并使用克隆对象而不是对同一对象的引用。