devdropper87 devdropper87 - 1 year ago 149
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

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
'd function in my routes file which exposes
in the dashboard controller:

widgets($http, $q, CacheFactory, WidgetsService) {
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);
gridsterConfig.draggable.stop = function(event, $element, widget) {
widgetsCache.put("widgets", $ctrl.widgets);
$ctrl.toggleVisibility = function(widget) {
widget.hidden = !widget.hidden;
widgetsCache.put("widgets", $ctrl.widgets);

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;

Answer Source

You can use resolve function for state to refetch the data you want. Please check

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download