Angularjs - Firebase显示用户数据中记录的当前数据

时间:2016-04-21 10:07:34

标签: javascript angularjs ionic-framework firebase

我正在尝试通过离子构建移动购物应用程序。我想显示用户添加到购物车中的商品。但是在网上找不到任何办法。 有人可以帮忙吗?

app.js

.constant('FURL', 'https://ecommayakkabi.firebaseio.com/')

controller.js

.controller('CartCtrl', function ($scope, $state, $cordovaOauth, $localStorage, $location, $http, $ionicPopup, $firebaseObject, Auth, FURL, Utils, basket) {
    var ref = new Firebase(FURL); --
    var user=ref.getAuth();
    if (user==null){
        console.log ('Should log in ');
        $state.go('login');
    } else {
        console.log ('loged ' + user.password.email);
        // can show here user's basket items but how?
    } 
});

services.js

  .factory("basket", function($firebaseArray) {
      var itemsRef = new Firebase("https://ecommayakkabi.firebaseio.com/items");
      return $firebaseArray(itemsRef);
  }) 

app.js

.state('tab.cart', {
    url: '/cart',
    cache: false,
    views: {
        'tab-cart': {
            templateUrl: 'templates/tab-cart.html',
            controller: 'CartCtrl'
        }
    }
});

firebase view

1 个答案:

答案 0 :(得分:1)

由于Firebase使用非规范化数据模式,因此您需要将项目写入/items/:userId,这样您就可以通过用户ID检索它们,而无需遍历所有/items路径,它将是Firebase -rules友好。

因此,在您向items/路径添加新项目的位置将其更改为:

var ref = new Firebase("https://ecommayakkabi.firebaseio.com");
var userId = ref.getAuth().uid;
ref.child("items").child(userId).push(yourItemIsThere);

然后您可以通过以下方式检索它:

var ref = new Firebase("https://ecommayakkabi.firebaseio.com");
var userItems = $firebaseArray(ref.child("items").child(user.uid));

您还需要在Firebase规则中添加相应的更改,以便只允许具有相应ID的用户访问items/:userId路径,其中包含可选部分,但如果没有,您的应用将不安全。< / p>

Firebase规则示例:

{
  "rules": {
    ".read": false,
    ".write": false,
    "items": {
      "$userId": {
        ".write": "auth.uid === $userId",
        ".read": "auth.uid === $userId"
      }
    }
  }
}

根据您的意见,添加部分的完整代码是:

var ref = new Firebase(FURL);
ref.child("items").child(user.uid).push({
  "email": user.password.email,
  "userId": user.uid,
  "product_id": "productId",
  "product_name": "product_name",
  "product_url": "product_url",
  "product_color": "product_color",
  "product_size": "product_size",
  "product_count": "product_count",
  "product_price": "product_price"
});

或者如果你想在那里使用$ firebaseArray:

var ref = new Firebase(FURL);
var userBasket = $firebaseArray(ref.child("items").child(user.uid));
userBasket.$add({
  "email": user.password.email,
  "userId": user.uid,
  "product_id": "productId",
  "product_name": "product_name",
  "product_url": "product_url",
  "product_color": "product_color",
  "product_size": "product_size",
  "product_count": "product_count",
  "product_price": "product_price"
});