Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Saving Data to Local Storage in Angular | Services and Dependency Injection in Angular
Introduction to Angular

bookSaving Data to Local Storage in Angular

At this stage, our application manages tasks only in memory. This means that every time the page is refreshed, the entire list of tasks is lost.

To fix this and make sure tasks are saved between user sessions, we'll use Local Storage β€” a built-in browser feature that allows you to store key-value pairs directly in the user's browser.

What Is Local Storage?

Note
Definition

Local Storage is a type of web storage provided by modern browsers that lets you store data locally on the user's device in the form of key-value pairs.

The data stored in Local Storage doesn't disappear when the page or browser is closed β€” it stays available even after a full browser restart.

LocalStorage only stores data as strings, so when working with objects or arrays, you'll need to convert them using JSON.stringify() before saving and JSON.parse() when retrieving.

Here are the main methods used to interact with Local Storage:

Adding Local Storage

To ensure that our tasks are saved even after a page reload, you need to implement persistence using the browser's Local Storage. This means you must teach our TaskService how to save tasks to local storage and how to load them back when the app starts.

Saving Tasks to Local Storage

First, you need a method that will take our internal tasks array and store it in the browser's Local Storage.

Here's how you can do that:

private saveTasks(): void {
  localStorage.setItem('tasks', JSON.stringify(this.tasks));
}

This method converts the tasks array into a JSON string using JSON.stringify. It then stores that string in localStorage under the key tasks.

Every time a task is added, deleted, or updated, you'll call this method to make sure our data is saved.

Loading Tasks from Local Storage

Next, we'll implement a method that loads the task list from Local Storage when the service is initialized.

private loadTasks(): Task[] {
  const data = localStorage.getItem('tasks');
  return data ? JSON.parse(data) : [];
}

This method tries to retrieve a value from localStorage using the same key tasks.

If the data exists, it parses the JSON string back into a TypeScript array. If there's nothing in storage, it returns an empty array to start fresh.

Loading Tasks on Service Initialization

We want to load existing tasks as soon as the service is created. To do this, we use the service constructor:

constructor() {
  this.tasks = this.loadTasks();
}

This ensures the tasks array is immediately populated with any previously saved data when the app starts.

Final Version of TaskService

All that's left is to make sure our task list is saved to Local Storage whenever a change occurs. This means we need to call the saveTasks method at the end of the addTask, deleteTask, and toggleTask methods to keep Local Storage in sync with our tasks list.

Here is how the complete TaskService looks with local storage functionality:

task-service.ts

task-service.ts

copy

By implementing saveTasks() and loadTasks() in our service, we've enabled our task manager to persist data across sessions. Now, whenever the user adds, completes, or deletes a task, those changes are stored in the browser and automatically restored the next time they open the app.

This gives our app a much more professional and reliable user experience.

1. What does the setItem() method do?

2. Where is the best place to load tasks from localStorage in an Angular service?

question mark

What does the setItem() method do?

Select the correct answer

question mark

Where is the best place to load tasks from localStorage in an Angular service?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 3.13

bookSaving Data to Local Storage in Angular

Swipe to show menu

At this stage, our application manages tasks only in memory. This means that every time the page is refreshed, the entire list of tasks is lost.

To fix this and make sure tasks are saved between user sessions, we'll use Local Storage β€” a built-in browser feature that allows you to store key-value pairs directly in the user's browser.

What Is Local Storage?

Note
Definition

Local Storage is a type of web storage provided by modern browsers that lets you store data locally on the user's device in the form of key-value pairs.

The data stored in Local Storage doesn't disappear when the page or browser is closed β€” it stays available even after a full browser restart.

LocalStorage only stores data as strings, so when working with objects or arrays, you'll need to convert them using JSON.stringify() before saving and JSON.parse() when retrieving.

Here are the main methods used to interact with Local Storage:

Adding Local Storage

To ensure that our tasks are saved even after a page reload, you need to implement persistence using the browser's Local Storage. This means you must teach our TaskService how to save tasks to local storage and how to load them back when the app starts.

Saving Tasks to Local Storage

First, you need a method that will take our internal tasks array and store it in the browser's Local Storage.

Here's how you can do that:

private saveTasks(): void {
  localStorage.setItem('tasks', JSON.stringify(this.tasks));
}

This method converts the tasks array into a JSON string using JSON.stringify. It then stores that string in localStorage under the key tasks.

Every time a task is added, deleted, or updated, you'll call this method to make sure our data is saved.

Loading Tasks from Local Storage

Next, we'll implement a method that loads the task list from Local Storage when the service is initialized.

private loadTasks(): Task[] {
  const data = localStorage.getItem('tasks');
  return data ? JSON.parse(data) : [];
}

This method tries to retrieve a value from localStorage using the same key tasks.

If the data exists, it parses the JSON string back into a TypeScript array. If there's nothing in storage, it returns an empty array to start fresh.

Loading Tasks on Service Initialization

We want to load existing tasks as soon as the service is created. To do this, we use the service constructor:

constructor() {
  this.tasks = this.loadTasks();
}

This ensures the tasks array is immediately populated with any previously saved data when the app starts.

Final Version of TaskService

All that's left is to make sure our task list is saved to Local Storage whenever a change occurs. This means we need to call the saveTasks method at the end of the addTask, deleteTask, and toggleTask methods to keep Local Storage in sync with our tasks list.

Here is how the complete TaskService looks with local storage functionality:

task-service.ts

task-service.ts

copy

By implementing saveTasks() and loadTasks() in our service, we've enabled our task manager to persist data across sessions. Now, whenever the user adds, completes, or deletes a task, those changes are stored in the browser and automatically restored the next time they open the app.

This gives our app a much more professional and reliable user experience.

1. What does the setItem() method do?

2. Where is the best place to load tasks from localStorage in an Angular service?

question mark

What does the setItem() method do?

Select the correct answer

question mark

Where is the best place to load tasks from localStorage in an Angular service?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 4. ChapterΒ 5
some-alt