How to auto-save data when application is offline in Angular 8?

27 Jun, 2020
Auto-saving the data comes into action when your application needs to work offline and the CDN(content delivery network) will fail. In this article, we are going to access the required steps that are intended to save your application locally when offline and submit it once a connection has prevailed.
Environment Setup:
Before comprising the libraries which make your app work offline make sure to download the actual file (example: angular.js).
For instance, we’ll have a basic file named app.js that contains our Angular code, and a html document which is index.html which contains all our html code.
<!DOCTYPE html>  <html lang="en"><head>    <meta charset="UTF-8">    <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app="app">          <div data-ng-controller="MainController">                  <!-- Main Form -->              </div>  <script src="angular.js"></script><script src="./app.js"></script>  </body></html>
Hence, let us take an example of data entry application and build a form which collects data about dogs. if you’re studying about the respective breed of the dog, your application may go offline occasionally depending on your situated location.
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Offline AutoSave data in Angular 8</title></head><body data-ng-app="app">      <div data-ng-controller="MainController">                  <form name="form.DogBreedForm"       novalidate data-ng-submit="save()">                      <label for="commonIdentity">                           Common Identity</label>            <input id="commonIdentity" type="text"                   data-ng-model="formData.commonIdentity">              <label for="breedName">Breed</label>            <select name="breedName" id="breedName"                     data-ng-model="formData.breedName">                <option value="first">First</option>                <option value="second">Second</option>                <option value="third">Third</option>            </select>                            <label for="BreedFeatures">                       Breed Features</label>            <input id="BreedFeatures"                    type="text"                   data-ng-model="formData.BreedFeatures">                        <button type="submit">Save Locally</button>            <button type="button"                    data-ng-click="sync()">Sync</button>          </form>          </div>        <script src="./angular.js"></script><script src="./app.js"></script>  </body></html>
Note that, we have added a new term data-ng-model for all the inputs. Lets create a parent object called $scope.formData for our input data models. 
$scope.save function will handle the data saving instance to the local storage and $scope.sync will handle the submitting operation when the application goes online.
The Output(When Offline):
Page Output (Enter the Values)
Now, we are offline hence it will show us the below.
Let’s now deep-dive into performing the functions and storing the data offline once the user enters the data in the form.
Save function– LocalStorage will save our data in string key-value pairs. 
The data which is being stored in the localStorage will accept the Strings. Below in save function, we declare a stringCopy variable, and a lcKey property on $scope.formData. We use timestamp which is a unique identifier.
JSON File
JSON format file is often used for imparting structured data over a network connection. It primarily transmits the data between a server and a web application. Hence while parsing the stringed JSON, if it is not valid, it throws an exception. In order to avoid these exceptions let’s make use of tr-catch block for handling it.
JSON stands for JavaScript Object Notation is an independent language and json is a format of data which agreeably permits us to share data with any platform. It distributes the data to any kind of medium and linking JSON is uncomplicated.
stringCopy = JSON.stringify($scope.formData);

  Parsing localStorage and saving to server- Saving your data to the local storage when you are offline using JSON.stringify. Now we use JSON.parse to sync the data to the database when your application goes online. 
Note–We Included a button to our html document to save and submit your data to the local storage inside the form section.
app.js File
App.js represents your main javascript file to design your NodeJs applications. The file have to be stored in the main app root directory. The file can also contain a different name(ex: main.js ). It builds an interface between nodejs functionalities and html code over your web application.
angular.module('app', [])    .controller('MainController', ['$scope', function ($scope) {        var fetchAll = function () {                                  var finds = [];                  if (localStorage.length === 0) {                    return [];                }                  for (var i=0;i<localStorage.length;i++) {                                          try {                        finds.push(JSON.parse(localStorage.getItem(localStorage.key(i))));                    } catch (err) {                        console.log(err);                    }                  }                  return finds;              };          $scope.formData = {};                $scope.save = function () {            var stringCopy = '';            $scope.formData.lcKey = Date.now().toString();            try {                stringCopy = JSON.stringify($scope.formData);            } catch (err) {                                    console.debug(err);                return;            }            localStorage[$scope.formData.lcKey] = stringCopy;          };                    $scope.sync = function () {              var records = fetchAll();                            if (navigator && navigator.onLine && records.length) {                      records.forEach(function (find, idx)                         $http({                            url: '/api/finds',                            method: 'POST',                            data: find                        }).then(function (res) {                                                 localStorage.removeItem(find.lcKey.toString());                 ecords.splice(idx); //remove from records array                          }, function (err) {                              //error handling - service call failures                          });                    });                    } else {                      //error handling - Alert the user for patience                }          };      }]);
Finally after syncing the data, The Output(When online):
We used the fetchAll function to automatically detect the connection and save your data and sync it to the database. We’ll call this in the in the submit function. Once the connection is established the data which is being stored in the localStorage will be synced by looping through the records stored one-by-one and submit them to the database.
Hence this article helps you to store your data locally to the localStorage when your application is offline and sync the data to the database when it gets online using $scope functions for the input and parsing them.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?