How to cache AngularJS UL router?

Not sure if this is the best way to formulate a question, but I want the permission to be executed once when the state changes. This is because I have several tabs, and I need to use an AJAX call to get the data for the template. Therefore, when you click on the tab, I will store this information in the $ area. But I do not want to continue this call if the user switches to another tab and returns.

Here is what my $ stateProvider looks like:

state('something', { views: { 'filters.form': { templateUrl: '<%= asset_path('my_path.html') %>', controller: function($scope, sources){ $scope.sources = sources; } } }, resolve: { sources: function($http) { return $http.get('/sources').success(function(data){ return JSON.parse(data.sources); }); } } }) 

Which works fine, but every time I switch tabs and return, it makes another call that I don't need.

I tried to pass the $ scope value to the resolution and checked if the $ scope.sources file existed before I made an AJAX call, but that didn't work.

+5
source share
1 answer

I would just move it to the service and cache it and paste it into the solution.

 app.service('SourceService',['$http', function(){ var _cachedPromise; this.getSources = function(){ return _cachedPromise || _cachedPromise = $http.get('/sources').then(function(result){ //return result.data.sources //If the data is already an object which most possibly is just do return JSON.parse(result.data.sources); }); } }]); 

Now in the solution do: -

  resolve: { sources: function(SourceService) { return SourceService.getSources(); } } 

or just do it in the resolution itself.

+5
source

Source: https://habr.com/ru/post/1200884/


All Articles