在angularjs应用程序中在哪里放置对firebase的重复调用? [英] Where to put duplicate calls to firebase in angularjs app?
问题描述
我需要在每个控制器中从 firebase 获取一组 products
,如果我不必每次都进行 API 调用,那将是理想的.使用 angularfire 库实现这一目标的最佳方法是什么?
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
现在我有(在 coffeescript 中):
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
有什么方法可以分解出 2 个控制器中的通用代码并在 $rootScope
(或类似)级别设置 products
以便我可以执行 <返回产品后,在 productCtrl
中的代码>_.find?
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?
推荐答案
正如@tymeJV 在他的评论中所说,我确实为数组设置了一个服务:
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;
}
然后简单地将其注入您的控制器而不是(或除了)$firebase
:
And then simply inject that into your controllers instead of (or in addition to) $firebase
:
app.controller 'catalogCtrl', ($scope, products) ->
$scope.products = products
return
在 我的 Trenches 应用程序中,我使用这种方法来设置这个微不足道的服务包装 $firebaseSimpleLogin
:
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;
});
还有一个不太重要的服务,它依赖于当前的 URL/路由(下面的简化片段,完整"代码在 github 上):
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,
}
});
这篇关于在angularjs应用程序中在哪里放置对firebase的重复调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!