当前位置:   article > 正文

meteor方法

meteor方法

1.Account

  1. login(phoneNumber: string, code: string): Promise<void> {
  2. return new Promise<void>((resolve, reject) => {
  3. Accounts.verifyPhone(phoneNumber, code, (e: Error) => {
  4. if (e) {
  5. return reject(e);
  6. }
  7. resolve();
  8. });
  9. });
  10. }

 

2.发布和订阅

1.在server端发布

  1. Meteor.publish('time', function() {
  2. ...
  3. });

2.在client端订阅

后面可以带参数或者控制器函数

Meteor.subscribe('time', id)
  1. Meteor.subscribe('time', {
  2. onReady: function() {
  3. console.log('the server called this.ready()')
  4. },
  5. onError: function() {
  6. console.log('error on the server')
  7. }
  8. });

客户端也要创建新的mongo实例,然后通过订阅后的服务器的数据会推送到该实例上,但是只存在于内存中,所有对数据库的操作必须通过服务器的mongo实例进行操作!

3.配合react事件函数取消订阅

  1. componentWillUnmount() {
  2. this.props.handle.stop();
  3. }
  4. export default createContainer(() => {
  5. return {
  6. time: Time.find().fetch(),
  7. handle: handle
  8. };
  9. }, Timer)
  1. const handle = Meteor.subscribe('time', {
  2.      onReady: function() {
  3. console.log('the server called this.ready()')
  4. },
  5. onError: function() {
  6. console.log('error on the server')
  7. }});
  8. handle.stop() // will call onStop(callback) on the server.
  9. handle.ready() // returns true if the server called ready()

4.在服务器端写就绪和取消订阅的处理

利用this.ready() this.stop() this.onStop()

  1. Meteor.publish('time', function() {
  2. let self = this;
  3. self.added('time', id, time); // notify if record is added to the collection time
  4.  this.ready(); // notify that the initial dataset was sent
  5. self.onStop(function () {
  6. self.stop()
  7. console.log('stopped called')
  8. Meteor.clearInterval(interval); // clear the interval if the the client unsubscribed
  9. });
  10. });

3.延迟函数

  1. Meteor.setInterval(function() {
  2. newTime();
  3. }, 1000);
  4. Meteor.clearInterval(interval);

4.数据库操作

默认可以直接在客户端对数据库进行操作,删除secure包后,只能调用服务器的方法对数据进行操作,而如果直接在客户端调用collection.insert()之类的方法,最终的结果只会存储在客户端的minimogo中

1.定义方法

  1. import { Meteor } from 'meteor/meteor';
  2. Meteor.methods({
  3. cartInsert: function(product) {
  4. CartCollection.insert({
  5. 'title' : product.title,
  6. 'price' : product.price,
  7. 'inventory' : product.inventory,
  8. 'quantity': 1
  9. });

2.然后在客户端使用

  1. import { Meteor } from 'meteor/meteor';
  2. export const addToCart = (product) => {
  3. Meteor.call('cartInsert', product);
  4. };

对于返回数值的可采用promise

  1. cartTotal: function() {
  2. let total = CartCollection.aggregate([
  3. { $project: {"priceByquantity":{ $multiply: [ "$price", "$quantity" ] } }},
  4. { $group: { "_id": "null", "totalPrice": { $sum: "$priceByquantity" } } }
  5. ]);
  6. return total;
  7. }

用aggregate计算总价钱,$project来产生一个"priceByquantity"的新键, "_id": "null"表示把所有的加起来,"totalPrice"为赋值的对象,最终得到的值包裹在data中

  1. export const getCartTotal = () => {
  2. return new Promise((resolve, reject) => {
  3. Meteor.call('cartTotal', (error, data) => {
  4. if (error) {
  5. reject(error)
  6. }
  7. if(!data[0]){
  8. resolve(0)
  9. }
  10. resolve(data[0].totalPrice)
  11. })
  12. });
  13. };

使用promise来包裹,利用then还有catch来对其中的数据进行操作

  1. getCartTotal().then(result => {
  2. self.setState({
  3. totalPrice: result
  4. })
  5. }).catch(error => {
  6. alert('error')
  7. });

由于promise是异步的,而container本身是异步的,其内部只能使用同步的方法,所以把getCartTotal()放在组件事件周期中使用

  1. componentDidMount()
  2. componentWillReceiveProps()

只有初始化和props改变的时候

5.验证和模型

  1. import { check } from 'meteor/check';
  2. check('title' : product.title,string)
  3. check( product, CartCollection.simpleSchema())

不常用!!

 meteor add aldeed:simple-schema
  1. let CartSchema = new SimpleSchema({
  2. _id: {
  3. type: String,
  4. optional: false
  5. },
  6. price: {
  7. type: Number,
  8. decimal: true   设为false则为整数
  9. },
  10. quantity: {
  11. type: Number,
  12. defaultValue: 1,
  13. optional: true
  14. },
  15. department: {
  16. type: String,
  17. optional: false
  18. }
  19. });

department是必须的,验证完模型后再insert

直接使用collection2会自动每次校正格式(meteor add aldeed:collection2)

  1. CartCollection.attachSchema(CartSchema)
  2. check( product, CartCollection.simpleSchema());
  1. //弃用
  2. CartCollection.schema.validate(product);
  3. CartCollection.schema.clean(product);
  4. check( product, CartCollection.schema);
  5. //在每次插入前去掉product里面不必要的部分,使其规范化
  6. CartCollection.insert({....})

6.用户登录

  1. meteor add accounts-password
  2. allanning:roles
  1. Accounts.creatUser({email:444,password:6665})
  2. Meteor.loginWithPassword(email,password)
  3. Meteor.logout(fuc(err){})
  4. Meteor.users.findOne()
  5. Meteor.user()--获取当前用户

转载于:https://my.oschina.net/yihong/blog/1530974

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/346452
推荐阅读
相关标签
  

闽ICP备14008679号