在angularjs app中将重复调用放到firebase的位置?

时间:2014-10-03 00:51:17

标签: angularjs firebase angularfire

我需要在每个控制器中从firebase获取一组products,如果我不必每次都进行API调用,那将是理想的选择。使用angularfire库实现这一目标的最佳方法是什么?

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

现在我(在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

有没有办法分解2个控制器中的公共代码,并在products(或类似)级别设置$rootScope,这样我就可以_.find productCtrl 1}}产品退回后?

1 个答案:

答案 0 :(得分:1)

正如@tymeJV在评论中所说,我确实为这个阵列设置了一个服务:

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;
}

然后简单地将其注入您的控制器而不是(或除了)$firebase

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

my trenches app我已经使用这种方法设置这个简单的服务包裹$firebaseSimpleLogin

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

一个不那么简单的服务取决于当前的URL /路由(下面的简化片段,“完整”代码在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,
    }
});