Meteor - 方法


Meteor 方法是在服务器端编写的函数,但可以从客户端调用。

在服务器端,我们将创建两个简单的方法。第一个将为我们的参数添加 5 ,而第二个将为我们的参数添加10

使用方法

流星App.js

	
if(Meteor.isServer) {

   Meteor.methods({

      method1: function (arg) {
         var result = arg + 5;
         return result;
      },

      method2: function (arg) {
         var result = arg + 10;
         return result;
      }
   });
}

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方法。以下示例显示如何处理未登录用户的错误。

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;
      }
   });
}

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);
   }});

}

控制台将显示我们定制的错误消息。

流星方法错误