How to optimise data retrieval and inter-controller data sharing with AngularFire automatic binding?

笑着哭i 提交于 2019-12-13 07:41:29

问题


Say I have

  1. a list view+controller that displays a list of item names and
  2. a detail view+controller thats shows detail for an item.

How would I use angularfire (preferably with automatic three way binding) in a way that does not fetch the same data twice?

Because controller#1 would have already fetched the items AND their details when the (itemsListRef).$bind($scope, 'items'); statement executes. In controller#2, (itemDetailRef,).$bind($scope, 'itemDetail') would then fetch item detail data that again that has already been fetched in controller#1.

One option that comes to mind : An angular service could be used to fetch the items data once and then share the data between controllers, but I am not sure how angularfire three-way automatic binding would play into this, or if it would even work. Your thoughts/advise on this? Any other options? What would be the recommended way to handle this?


回答1:


The Firebase client is smart enough to use a local cache if it exists. Firebase instances are singletons for each base Firebase URL, so attaching multiple listeners at varying paths in the same Firebase will not result in unnecessary network activity.

I recommend creating a $firebase reference in a service, and then using a 3-way data bind for the details of the item in a controller. For example:

var myapp = angular.module("myapp", ["firebase"]);

myapp.factory("ItemService", ["$firebase", function($firebase) {
  return $firebase(itemsListRef);
}]);

myapp.controller("DetailCtrl", ["$scope", "ItemService", function($scope, items) {
  items.$child(itemId).$bind($scope, 'itemDetail');
}]);


来源:https://stackoverflow.com/questions/21824796/how-to-optimise-data-retrieval-and-inter-controller-data-sharing-with-angularfir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!