2016-03-15 2 views
0
if(Meteor.isClient) 
    { 
     userKey = localStorage.getItem("user_key"); 
     if(!userKey){ 
      userKey = Meteor.uuid(); 
      localStorage.setItem("user_key", userKey); 
     } 

     getCart = function(next){ 
      Meteor.call("getCart", next); 
     }; 

     addToCart = function (id, callback) { 
      Meteor.call('addToCart',userKey, id, callback); 
     }; 
     removeFromCart = function (id, callback) { 
      Meteor.call('removeFromCart',userKey, id, callback); 
     }; 
     updateCart = function (id, quantity, callback) { 
      Meteor.call('updateCart', userKey, id, quantity, callback); 
     }; 
    } 

    if(Meteor.isServer) { 
     Meteor.methods({ 

      "getCart": function (userKey) { 
       check(userKey, String); 
       return Carts.getCart(userKey); 
      }, 
      "addToCart": function (userKey, id) { 
       check(userKey, String); 
       check(id, String); 
       var cart = Meteor.call("getCart", userKey); 

       //get the item in the cart 
       var found = _.find(cart.items, function (item) { 
        return item._id === id; 
       }); 

       if (found) 
       { 
        found.quantity++; 
       } 
       else 
       { 
        //add the item 
        var product = Products.findOne({_id: id}); 
        var item = { 
         id: product._id, 
         name: product.productName, 
         price: product.price, 
         shop: product.shop, 
         image: product.productImg, 
         discount: 0, 
         added_at: new Date(), 
         quantity: 1 
        }; 
        cart.items.push(item); 

       } 
       cart.notes.push({ 
        note: id + " added to cart", 
        created_at: new Date() 
       }); 
       //save it 
       Meteor.call("saveCart", cart); 
       return cart; 
      }, 
      "updateCart": function (userKey, id, quantity) 
      { 
       check(userKey, String); 
       check(id, String); 
       check(quantity, Match.Where(function (quantity) 
       { 
        check(quantity, Number); 
        return quantity >= 0; 
       })); 
       var cart = Meteor.call("getCart", userKey); 
       //only update the quantity here 
       _.each(cart.items, function (item) 
       { 
        if (item._id === id) 
        { 
         item.quantity = quantity; 
         return Meteor.call("saveCart", cart); 
        } 
       }); 
      }, 
      "removeFromCart": function (userKey, id) 
      { 
       check(userKey, String); 
       check(id, String); 
       var cart = Meteor.call("getCart", userKey); 
       //get the item in the cart 

       var found = _.find(cart.items, function (item) 
       { 
        return item._id === id; 
       }); 

       if (found) 
       { 
        var foundIndex = cart.items.indexOf(found); 
        cart.items.splice(foundIndex, 1); 
        cart.notes.push({ 
         note: id + " removed from cart", 
         created_at: new Date() 
        }); 
        Meteor.call("saveCart", cart); 
       } 

       return cart; 
      }, 
      "saveCart": function (cart) { 
       check(cart, Match.ObjectIncluding({ 
        userKey: String, 
        items: [Match.ObjectIncluding({ 
         id: String 
        })] 
       })); 

       var products = Products.find({ 
        _id: {$in: _.pluck(cart.items, '_id')} 
       }).fetch(); 

       var skuMap = _.object(_.pluck(products, '_id'), products); 

       cart.updated_at = new Date(); 
       cart.total = 0; 
       var counter = 0; 
       _.each(cart.items, function (item) 
       { 
        item.price = skuMap[item._id].price; 
        item.quantity = Math.max(0, item.quantity); 
        // TODO: Don't trust discount from client 
        item.lineTotal = (item.price - item.discount) * item.quantity; 
        cart.total += item.lineTotal; 
        counter++; 
       }); 
       cart.itemCount = counter; 
       Carts.update({userKey: cart.userKey}, cart, {upsert: true}); 
       return cart; 
      }, 
      "emptyCart": function (userKey) 
      { 
       check(userKey, String); 
       Carts.remove({userKey: userKey}); 
      } 
     }) 
    } 

Код, приведенный выше, относится к простой системе тележек. Получает пользователей uuid, устанавливает это как user_key и делает нормальное добавление в корзину, получает тележку и обновляет операции с корзиной. Я проверил мой браузер, и я знаю, что пользовательский ключ устанавливается в localStorage, но когда я вызываю метод addToCart, я продолжаю получать следующую ошибку на изображении ниже.Я продолжаю получать опорную ошибку, что user_key не определен

enter image description here
Это моя служба Carts.getCart ниже.

Carts.getCart = function() 
{ 
    var cart = Carts.findOne({userKey : userKey}); 

    if(!cart){ 
     cart = { 
      userKey : userKey, 
      email : null, 
      name :null, 
      ip : null, 
      created_at : new Date(), 
      items : [], 
      notes : [{ 
       note : "Cart created", 
       created_at : new Date() 
      }], 
      status : "open", 
      itemCount : 0, 
      total : 0 
     }; 
    } 
    return cart; 
}; 

ответ

0

, кажется, вам нужно добавить вар, прежде чем userKey:

var userKey = localStorage.getItem("user_key"); 

Также попытайтесь сохранить в сессии и получить значение:

localStorage.setItem("user_key", userKey); 
Session.set("user_key", localStorage.getItem(userKey)); 
+0

Я пробовал, но это не сработало – lagfvu

0

я нашел проблему, я забыл передать в userkey функции getCart

Смежные вопросы