devdropper87 devdropper87 - 29 days ago 15
AngularJS Question

how to refresh data in cache on state reload- angular 1.5 / ui-router

I am working on a task where I have a bunch of widgets on a dashboard. When the user changes the customer on the dashboard the

$state
is reloaded, and the widgets' position should be saved to a cache, but the data relevant to the widgets should be refreshed. There are two relevant components, a header component where the customer is changed, and the dashboard component where the widgets are. I'd like to accomplish this without touching the header component.

Previously, I wrote a function to remove all data related properties from the cache after saving in the cache, but I think that might not be the right approach and too complicated. what is the best way to accomplish this?

so suppose each widget looks like this:

{
widgetType: chart,
position: someCoordinatesThatStayTheSameOnStateChange,
chart: containsDataThatNeedsToBeRefreshed,
chartData: containsDataThatNeedsToBeRefreshed
}


this is a
$resolve
'd function in my routes file which exposes
$ctrl.widgets
in the dashboard controller:

widgets($http, $q, CacheFactory, WidgetsService) {
'ngInject';
let mockWidgetData = WidgetsService.getAllWidgets();
let widgetsCache = CacheFactory.get('widgets');
if (!widgetsCache) {
CacheFactory.createCache('widgets', {
storageMode: 'localStorage',
});
}
return mockWidgetData;
},


relevant places where I save data in a cache in the dashboard controller:

let widgetsCache = CacheFactory.get('widgets');
let widgetsCacheItems = widgetsCache.get('widgets');

gridsterConfig.resizable.stop = function(event, $element, widget) {
widgetsCache.put("widgets", $ctrl.widgets);
//clearDataFromCache()
}
gridsterConfig.draggable.stop = function(event, $element, widget) {
widgetsCache.put("widgets", $ctrl.widgets);
//clearDataFromCache()
}
$ctrl.toggleVisibility = function(widget) {
widget.hidden = !widget.hidden;
widgetsCache.put("widgets", $ctrl.widgets);
//clearDataFromCache()
}


old function I wrote:

function clearDataFromCache() {
let widgetObjectsInCache = widgetsCache.get('widgets');
widgetObjectsInCache.forEach((widget) => {
if (widget.chart) delete widget.chart;
if (widget.chartConfig) delete widget.chartConfig;
})
console.log(widgetObjectsInCache, "THE CACHE AFTER REMOVING ANY DATA RELATED STUFF");
}

Answer

You can use resolve function for state to refetch the data you want. Please check https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c?swoff=true#.bkudisx52

Comments