Don't reload page when clicking back button - AngularJS

I am developing an AJAX-heavy application with AngularJS and need requests so as not to be redone when the user clicks the back button in my browser. For example, a data set takes 2-3 seconds to load, and then if the user goes to another page and then clicks back, the data must be reloaded. Is there a way to prevent this - or, alternatively, another way to develop my application so that data is saved through the session?

+4
source share
3 answers

If you use ngResource to load data from the api, set the cache value to true in actions, as described in the documentation

cache - {boolean | Cache} - If true, the default cache address $ http will be used to cache the GET request, otherwise if the cache instance built with $ cacheFactory, this cache will be used for caching.

https://docs.angularjs.org/api/ngResource/service/ $ resource

Example:

this.service=$resource('www.example.com/api/v/stats',
        {
            callback: "JSON_CALLBACK"
        }, {'foo': {'method': 'GET', 'cache': true}}
    );

Loading data through this.service.foo () will cache the request button and vice versa, it will use cached data instead of reloading.

+1
source

I highly recommend that you learn more about using routing with AngularJS.

, : https://egghead.io/lessons/angularjs-ng-view

, , , : https://egghead.io/lessons/angularjs-route-life-cycle

, .

0

, , $routeProvider . - :

$routeProvider.when(/someModule/page1Condition1, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});
$routeProvider.when(/someModule/page1Condition2, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});

page1 - :

if($location.path()==='/someModule/page1Condition2){
    // something that should be done only when Condition2 is true,
    // for example, loading data using ajax
    $http.get('somePath')
        .success(function(data){
            $scope.myData = angular.fromJson(data);
        });
} 

This way, I only have one controller, but conditionally retrieve data using a URL as a source of information. Think of it as wanting to be as close to REST as possible, but not really REST.

It is important to note that I also have some strange requirements imposed by my client, so this is probably not the best way to solve this problem (it may even be antipattern, although I like to think that this is just a temporary hack).

0
source

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


All Articles