博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
meteor方法
阅读量:7208 次
发布时间:2019-06-29

本文共 4285 字,大约阅读时间需要 14 分钟。

hot3.png

1.Account

login(phoneNumber: string, code: string): Promise
{ return new Promise
((resolve, reject) => { Accounts.verifyPhone(phoneNumber, code, (e: Error) => { if (e) { return reject(e); } resolve(); }); }); }

 

2.发布和订阅

1.在server端发布

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

2.在client端订阅

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

Meteor.subscribe('time', id)
Meteor.subscribe('time', {          onReady: function() {            console.log('the server called this.ready()')         },         onError: function() {           console.log('error on the server')         }});

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

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

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

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

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

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

3.延迟函数

Meteor.setInterval(function() {        newTime();     }, 1000); Meteor.clearInterval(interval);

4.数据库操作

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

1.定义方法

import { Meteor } from 'meteor/meteor';Meteor.methods({cartInsert: function(product) {      CartCollection.insert({       'title' : product.title,       'price' : product.price,       'inventory' : product.inventory,       'quantity': 1 });

2.然后在客户端使用

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

对于返回数值的可采用promise

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

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

export const getCartTotal = () => {  return new Promise((resolve, reject) => { Meteor.call('cartTotal', (error, data) => {       if (error) {          reject(error)      }     if(!data[0]){        resolve(0)     }      resolve(data[0].totalPrice)    }) });};

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

getCartTotal().then(result => {      self.setState({        totalPrice: result      })    }).catch(error => {      alert('error')    });

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

componentDidMount()  componentWillReceiveProps()

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

5.验证和模型

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

不常用!!

meteor add aldeed:simple-schema
let CartSchema = new SimpleSchema({  _id: {    type: String,    optional: false  },  price: {    type: Number,    decimal: true   设为false则为整数  },  quantity: {    type: Number,    defaultValue: 1,    optional: true  },  department: {    type: String,    optional: false  }});

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

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

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

6.用户登录

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

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

你可能感兴趣的文章
10.cadence.自定义焊盘的创建[原创]
查看>>
shell编程总结
查看>>
Docker源码分析(七):Docker Container网络 (上)
查看>>
一些旁门左道
查看>>
Common Pitfalls In Machine Learning Projects
查看>>
Android内存泄漏分析及调试
查看>>
todoing
查看>>
[Cocos2d-x]Cocos2d-x 3.2 学习笔记
查看>>
进程调度
查看>>
使用代码为TextView设置drawableLeft
查看>>
Android开发(十八)——头部、中部、底部布局技巧
查看>>
Egret 集成第三方库 记录
查看>>
同源策略——浏览器安全卫士
查看>>
c/c++ 基金会(七) 功能覆盖,虚函数,纯虚函数控制
查看>>
CodeForces 484B Maximum Value
查看>>
strong vs copy
查看>>
Codeforces Round #313 (Div. 1) C. Gerald and Giant Chess DP
查看>>
基于jQuery商城网站全屏图片切换代码
查看>>
Android开发之注解式框架ButterKnife在ADT中的设置
查看>>
JAVA学习篇--Java类加载
查看>>