Meteor - Phương pháp
Các phương thức sao băng là các hàm được viết ở phía máy chủ, nhưng có thể được gọi từ phía máy khách.
Ở phía máy chủ, chúng tôi sẽ tạo hai phương pháp đơn giản. Cái đầu tiên sẽ thêm 5 vào đối số của chúng ta, trong khi cái thứ hai sẽ thêm10.
Sử dụng phương pháp
meteorApp.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);
}
});
}
Sau khi khởi động ứng dụng, chúng ta sẽ thấy các giá trị được tính toán trong bảng điều khiển.
![](https://post.nghiatu.com/assets/tutorial/meteor/images/meteor-methods-log.jpg)
Xử lý lỗi
Để xử lý lỗi, bạn có thể sử dụng Meteor.Errorphương pháp. Ví dụ sau đây cho thấy cách xử lý lỗi cho người dùng chưa đăng nhập.
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);
}});
}
Bảng điều khiển sẽ hiển thị thông báo lỗi tùy chỉnh của chúng tôi.
![](https://post.nghiatu.com/assets/tutorial/meteor/images/meteor-methods-error.jpg)