【问题标题】:Where to put duplicate calls to firebase in angularjs app?在 angularjs 应用程序中对 firebase 的重复调用放在哪里?
【发布时间】:2014-10-03 00:51:16
【问题描述】:

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

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

现在我有(在咖啡脚本中):

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

有什么方法可以将两个控制器中的公共代码分解出来,并将products 设置为$rootScope(或类似)级别,这样我就可以在产品完成后在productCtrl 中执行_.find退了吗?

【问题讨论】:

  • 创建一个服务,并在该服务中让您的数据变量以空值开始。在第一次 firebase 调用时,设置您的数据变量,然后在每次后续调用中检查 null,如果为 null,则再次从 firebase 检索,否则使用存储的内容。

标签: angularjs firebase angularfire


【解决方案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/路由(下面是简化的 sn-p,“完整”代码在 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,
    }
});

【讨论】:

  • 感谢您的详细回复。我将如何在数组中找到product?当我尝试_.find 时,我遇到了数组尚未返回的问题。我应该在上述流程中的哪个位置找到?
  • 阅读 AngularFire 返回的承诺。在这种情况下products.$loaded().then(function(products) { _.find(... (firebase.com/docs/web/libraries/angular/…)。但在 Angular 方面,我更早希望您通过其 id 将您正在寻找的对象绑定到 $scope。请注意,您的原始问题中不存在这些。
  • 我最初的问题是关于如何执行_.find。抱歉,如果不清楚。我明天会试试这个,如果它有效,奖励你解决方案。
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 2018-07-07
  • 1970-01-01
  • 2014-07-03
相关资源
最近更新 更多