Meteor方法是写入在服务器侧的函数,但可以在客户端调用这些函数。
在服务器端,我们将创建两个简单的方法。第一个参数将加5,而第二个参数将加10。
使用方法
meteorApp/server/main.js
if(Meteor.isServer) {
Meteor.methods({
method1: function (arg) {
var result = arg + 5;
return result;
},
method2: function (arg) {
var result = arg + 10;
return result;
}
});
}
meteorApp/client/app.js
if(Meteor.isClient) {
var aaa = 'aaa'
Meteor.call('method1', aaa, function (error, result) {
if (error) {
console.log(error);
else {
console.log('Method 1 result is: ' + result);
}
}
);
Meteor.call('method2', 5, function (error, result) {
if (error) {
console.log(error);
} else {
console.log('Method 2 result is: ' + result);
}
});
}
当我们启动应用程序,我们将看到在控制台输出的计算值。


处理错误
如需处理错误,可以使用 Meteor.Error 方法。下面的例子说明如何为未登录用户处理错误。
meteorApp/server/main.jsimport { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
// code to run on server at startup
});
if(Meteor.isServer) {
Meteor.methods({
method1: function (param) {
if (! this.userId) {
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
}
return result;
}
});
}
meteorApp/client/app.js
if(Meteor.isClient) { Meteor.call('method1', 1, function (error, result) {
if (error && error.error === "logged-out") {
console.log("errorMessage:", "Please log in to post a comment.");
} else {
console.log('Method 1 result is: ' + result);
}});
}
控制台将显示我们的自定义错误消息。


上一篇:
Meteor帐号
下一篇:
Meteor package.js
