There are libraries you can use that give you a wider range, more generic, robust methods to manage the data in the local storage. Here we will implement a simple solution.
localStorageinstance which is exposed to us globally. That means that we can call all available methods in this interface by simply using this instance.
setItem. Here's an example of using them:
clear. It's used to clear all the data from local storage:
storage.service.ts, will be created with the following code:
As mentioned above, this service could have a wider API with more robust methods. When you write a service for accessing a database you will have other methods for adding, modifying and deleting specific items.
TodoListService. First we'll inject the
TodoListService, just like we injected the latter into
ListManagerComponent. We'll ask for an instance of the service in the constructor, and make sure its class is imported. We'll move the default todo list outside the class. We'll also add a constant with the key of our storage.
A better practice is to use the environments files for storing keys. This way you can manage different keys for each environment - development, production, staging, etc.
todoListproperty. We'll initialize it in the constructor with either the list in the local storage, if exists, or the default one.
...item) which are overridden by the keys and values of
changes. (If a key in
changesdoesn't exist in
item, it is added to the new object.)
nitems starting from index
i. In our code, we remove only one item (that's why we use 1 as the second parameter).
localStorageis a great and a pretty straight-forward tool for developers to store data locally on the users' computers/devices. We then implemented a new service that uses
localStorageto store data, which our
TodoListServiceuses to save the todo-list items.