Tyler
Tyler

Reputation: 11509

Where to put duplicate calls to firebase in angularjs app?

I need to get a set of products from firebase in every controller, and it would be ideal if I don't have to make an API call every single time. What is the best way to achieve this with the angularfire library?

https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray

Right now I have (in coffeescript):

app = angular.module 'EApp', ['ui.router', 'firebase']

app.config ($stateProvider, $urlRouterProvider) ->

  $stateProvider
    .state 'catalog',
      url: '/catalog'
      templateUrl: 'partials/catalog.html'
      controller: 'catalogCtrl'
    .state 'product',
      url: '/product/:id'
      templateUrl: 'partials/product.html'
      controller: 'productCtrl'

  $urlRouterProvider.otherwise 'catalog'
  return

app.controller 'catalogCtrl', ($scope, $rootScope, $firebase) ->
  ref = new Firebase("https://my-url.firebaseIO.com/")
  $scope.products = $firebase(ref).$asArray()
  return

app.controller 'productCtrl', ($scope, $rootScope, $stateParams, $firebase) ->
  ref = new Firebase("https://my-url.firebaseIO.com/")
  $scope.products = $firebase(ref).$asArray()
  return

Is there any way to factor out the common code in the 2 controllers and set products at the $rootScope (or similar) level such that I can do a _.find in productCtrl once the products have been returned?

Upvotes: 1

Views: 151

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599051

As @tymeJV says in his comment, I'd indeed set up a service for the array:

app.constant('FBURL', "https://my-url.firebaseio.com/");
app.factory('products', function($firebase, FBURL) {
    var ref = new Firebase(FBURL);  
    var products = $firebase(ref).$asArray();
    return products;
}

And then simply inject that into your controllers instead of (or in addition to) $firebase:

app.controller 'catalogCtrl', ($scope, products) ->
    $scope.products = products
    return

In my trenches app I've used this approach to set up this trivial service wrapping $firebaseSimpleLogin:

app.factory('$firebaseAuth', function($firebase, $firebaseSimpleLogin, FBURL) {
    var auth = $firebaseSimpleLogin(new Firebase(FBURL));
    return auth;
});

And a somewhat less trivial service that depends on the current URL/route (simplified snippet below, "full" code is on github):

app.factory('board', function($firebase, $firebaseAuth, FBURL, $routeParams) {
    var ref = new Firebase(FBURL+"boards/"+$routeParams.boardId);    
    var cards = $firebase(ref.child('cards')).$asArray();    
    return {
        ref: ref,
        id: $routeParams.boardId,
        cards: cards,
    }
});

Upvotes: 1

Related Questions