Meteor方法


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.js
import { 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);
   }});
}
控制台將顯示我們的自定義錯誤訊息。