1

I am new to firebase and angularjs. For my sales application I would like to use both. So, in my app I am using AngularJS v1.5.8 + Firebase v3.3.0 + AngularFire 2.0.2. I have sales and users objects in firebase db, and has a business logic that one user can sell multiple products, but one product can have only one owner (user).

Here is the users and sales objects in database:

{
  "sales" : {
    "-KQlb5N6A9rclc5qcWGD" : {
      "price" : 8,
      "quantity" : {
        "count" : 12,
        "type" : "porsiyon"
      },
      "status" : "sale",
      "title" : "Patlicanli Borek",
      "user" : "-KQ52OJd-lwoDIWzfYFT"
    },
    "-KQlcScsq8cidk7Drs04" : {
      "price" : 12,
      "quantity" : {
        "count" : 10,
        "type" : "porsiyon"
      },
      "status" : "sale",
      "title" : "Deneme",
      "user" : "-KQ5-mZBt6MhYy401gGM"
    },
    "-KQzXHwOv2rC73scjV46" : {
      "price" : 12,
      "quantity" : {
        "count" : 11,
        "type" : "porsiyon"
      },
      "status" : "sale",
      "title" : "Pacanga",
      "user" : "-KQ5-mZBt6MhYy401gGM"
    },
    "-KSCBgpArtnKunUuEuVr" : {
      "price" : 15,
      "quantity" : {
        "count" : 15,
        "type" : "porsiyon"
      },
      "status" : "sale",
      "title" : "Iskembe",
      "user" : "-KQ52OJd-lwoDIWzfYFT"
    }
  },
  "users" : {
    "-KQ5-mZBt6MhYy401gGM" : {
      "address" : "Halkali kucukcekmece",
      "email" : "burak.kahraman@gmail.com",
      "name" : "Burak Hero",
      "nick" : "Burak'in Mutfagi"
    },
    "-KQ52OJd-lwoDIWzfYFT" : {
      "address" : "Izmir kaynaklar",
      "email" : "ayse@gmail.com",
      "name" : "Ayse Kahraman",
      "nick" : "Ayse'nin Mutfagi"
    }
  }
}

What I want to do is when my app is opened, it will show all sales together with corresponding user details. (just like main page of letgo application) Which means I should implement a simple join between sales and users objects. As far as I searched throughout internet and api docs, there is no way to implement this kind of join in a single call to firebase. (Pl correct me if I am wrong) So I used below method with using $loaded function inside of my SalesService to implement join.

angular.
  module('core.sales')
  .service('SalesService', function ($firebaseArray, $firebaseObject, UsersService) {
this.getAllSalesJoin = function () {
      var sales;
      var refSales = firebase.database().ref('sales');
      sales = $firebaseObject(refSales);
      sales.$loaded()
        .then(function () {
          angular.forEach(sales, function (sale) {
            var saleUser = UsersService.getUserDetail(sale.user);
            saleUser.$loaded()
              .then(function () {
                sale.user = saleUser;
              });
          });
        });
      return sales;
    };
 });

As you see I am fetching all sales, after it finishes, looping for each sale to get and set related user detail by calling another UsersService shown below

angular.
  module('core.users')
  .service('UsersService', function ($firebaseArray,$firebaseObject) {
this.getUserDetail = function (userId) {
      var user;
      var refUser = firebase.database().ref('users/'+userId);
      user = $firebaseObject(refUser);
      return user;
    };
  });

So far so good, when I call SalesService.getAllSalesJoin function within my Controller and print the JSON object using <pre>{{$ctrl.allSales | json}}</pre>, everything works as I wanted, below is the Controller code and printed JSON object in the template.

angular.
  module('saleList').
  component('saleList', {
    templateUrl: 'MCTs/sale-list/sale-list-template.html',
    controller: ['SalesService','UsersService', function SaleListController(SalesService,UsersService,$scope) {

          this.allSales = SalesService.getAllSalesJoin();  
 }]
  });

Template shows the merged objects

{
  "$id": "sales",
  "$priority": null,
  "-KQlb5N6A9rclc5qcWGD": {
    "price": 8,
    "quantity": {
      "count": 12,
      "type": "porsiyon"
    },
    "status": "sale",
    "title": "Patlicanli Borek",
    "user": {
      "$id": "-KQ52OJd-lwoDIWzfYFT",
      "$priority": null,
      "address": "Izmir kaynaklar",
      "email": "ayse@gmail.com",
      "name": "Ayse Kahraman",
      "nick": "Ayse'nin Mutfagi"
    }
  },
  "-KQlcScsq8cidk7Drs04": {
    "price": 12,
    "quantity": {
      "count": 10,
      "type": "porsiyon"
    },
    "status": "sale",
    "title": "Deneme",
    "user": {
      "$id": "-KQ5-mZBt6MhYy401gGM",
      "$priority": null,
      "address": "Halkali kucukcekmece",
      "email": "burak.kahraman@gmail.com",
      "name": "Burak Hero",
      "nick": "Burak'in Mutfagi"
    }
  },
.....

But the problem is, when server data is changed (new sale is entered or old one is deleted), angular automatically understands the change but it applies the change to the view without implementing or calling my joined function, it simply prints only the sales object not the merged one with users. Below is the showing object after server data is changed.

{
  "$id": "sales",
  "$priority": null,
  "-KQlb5N6A9rclc5qcWGD": {
    "price": 8,
    "quantity": {
      "count": 12,
      "type": "porsiyon"
    },
    "status": "sale",
    "title": "Patlicanli Borek",
    "user": "-KQ52OJd-lwoDIWzfYFT"
  },
  "-KQlcScsq8cidk7Drs04": {
    "price": 12,
    "quantity": {
      "count": 10,
      "type": "porsiyon"
    },
    "status": "sale",
    "title": "Deneme",
    "user": "-KQ5-mZBt6MhYy401gGM"
  },
....

I am confused why it behaves like that? Is my way to implement join using $loaded wrong? Or should I use another method to implement this kind of join? I am looking forward to see your priceless suggestions and ideas.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

$loaded() only fires when the initial data has loaded. From the reference documentation (emphasis mine):

Returns a promise which is resolved when the initial object data has been downloaded from the database.

This is the main reason I often say: "if you're using $loaded(), you're doing it wrong".

You're right about needing to join data with multiple calls. In AngularFire you can extend $firebaseArray to perform such an operation. For a great example of how to do this, see this answer by Kato: Joining data between paths based on id using AngularFire

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

Thank for the guide @Frank. I read all your suggestions and found the solution. For contributing stackoverflow knowledge and to help others here is the complete solution for the problem.

I first created a new factory that extends $firebaseArray and override $$added and $$updated methods to perform join to Users object each time when the data is updated or added.

angular.
  module('core.sales').factory("SalesFactory", function ($firebaseArray, Sales) {
    return $firebaseArray.$extend({
      $$added: function (snap) {
        return new Sales(snap);
      },

      $$updated: function (snap) {
        return this.$getRecord(snap.key).update(snap);
      }

    });
  });

angular.
  module('core.sales').factory("Sales", function ($firebaseArray, $firebaseObject) {
    var refUsers = firebase.database().ref('users');

    function Sales(snapshot) {
      this.$id = snapshot.key;

      this.update(snapshot);
    }

    Sales.prototype = {
      update: function (snapshot) {
        var oldTitle = angular.extend({}, this.title);
        var oldPrice = angular.extend({}, this.price);
        var oldQuantity = angular.extend({}, this.quantity);

        this.userId = snapshot.val().user;
        this.title = snapshot.val().title;
        this.status = snapshot.val().status;
        this.price = snapshot.val().price;
        this.quantity = snapshot.val().quantity;
        this.userObj = $firebaseObject(refUsers.child(this.userId));

        if (oldTitle == this.title && oldPrice == this.price && 
        oldQuantity.count == this.quantity.count && oldQuantity.type == this.quantity.type)
          return false;
        return true;

      },

    };

    return Sales;
  });

As you see, SalesFactory uses another factory called Sales. In that particular factory I retrieve all properties of Sales object and assign each of them to its corresponding property. And that is the case I am performing join to Users object by creating new property : this.userObj One thing is missing that is just calling the new Factory instead of $firebaseArray

this.getAllSalesArray = function () {
      var sales;
      var refSales = firebase.database().ref('sales');
      sales = SalesFactory(refSales);
      return sales;
    };

All in all, all Sales object joined with related User is printed to the view is,

[
  {
    "$id": "-KQlb5N6A9rclc5qcWGD",
    "userId": "-KQ52OJd-lwoDIWzfYFT",
    "title": "Patlicanli Borek",
    "status": "sale",
    "price": 12,
    "quantity": {
      "count": 11,
      "type": "tabak"
    },
    "userObj": {
      "$id": "-KQ52OJd-lwoDIWzfYFT",
      "$priority": null,
      "address": "İzmir kaynaklar",
      "email": "ayse@gmail.com",
      "name": "Ayşe Kahraman",
      "nick": "Ayşe'nin Mutfağı"
    }
  },
  {
    "$id": "-KQlcScsq8cidk7Drs04",
    "userId": "-KQ5-mZBt6MhYy401gGM",
    "title": "Deneme",
    "status": "sale",
    "price": 12,
    "quantity": {
      "count": 10,
      "type": "porsiyon"
    },
    "userObj": {
      "$id": "-KQ5-mZBt6MhYy401gGM",
      "$priority": null,
      "address": "Halkalı küçükçekmece",
      "email": "burak.kahraman@gmail.com",
      "name": "Burak Hero",
      "nick": "Burak'ın Mutfağı"
    }
  },
...
]
Community
  • 1
  • 1