How to auto-save data when application is offline in Angular 8?
Last Updated :
29 Sep, 2022
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.
html
<!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.
javascript
<!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.
We are Offline
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 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 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.
javascript
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):
Data will be saved to your localhost
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 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.
Similar Reads
How to refresh entire application when date is changed in angular 9 ? In this example, we will see how to refresh the application when the date is changed in angularJS. Approach: First, we need to write the code for displaying the date picker in an HTML file.We can achieve this by giving the input type as the date.After completing the input type, we need to declare a
2 min read
How to build progressive web app(PWA) in Angular 9 ? In this article, we will develop a PWA (Progressive Web App) using Angular. What is PWA ? Progressive Web Apps (PWAs) are web applications that have been designed so that they are capable, reliable, and installable. PWA are built and enhanced with modern APIs to deliver enhanced capabilities, reliab
7 min read
How to Create a new module in Angular ? Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
How to Dockerize Angular Application Dockerizing an Angular application involves packaging it into a Docker container, which can simplify deployment and ensure consistency across different environments. Docker is a containerization platform that allows you to package applications and their dependencies into lightweight, portable contai
5 min read
How to achieve Two-Way Data Binding in Angular with ngModel ? Two-way Data Binding in Angular allows you to automatically synchronize data between a component class property and an input element (e.g., an input field) in your template. To achieve this binding, it's typically used with Angular [(ngModel)] Â directive. This is basically the combination of the Pro
3 min read
Purpose of the ngOnInit() method in Angular ngOnInit is a lifecycle hook in Angular that is called after the constructor is called and after the componentâs inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions
3 min read