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

Contenido del Curso

Introduction to Angular

Introduction to Angular

1. Angular Fundamentals
2. Components and Templates
3. Mastering Angular Directives and Pipes
4. Services and Dependency Injection in Angular
5. Standalone Components & Modules
6. Routing and Navigation in Angular

book
Saving 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, we need to implement persistence using the browser's Local Storage. This means we 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:

ts

example

copy
123
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, we'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.

ts

example

copy
1234
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:

ts

example

copy
123
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:

ts

task-service

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
import { Injectable } from '@angular/core'; export interface Task { id: number; title: string; completed: boolean; } @Injectable({ providedIn: 'root' }) export class TaskService { private tasks: Task[] = []; constructor() { this.tasks = this.loadTasks(); } private saveTasks(): void { localStorage.setItem('tasks', JSON.stringify(this.tasks)); } private loadTasks(): Task[] { const data = localStorage.getItem('tasks'); return data ? JSON.parse(data) : []; } getTasks(): Task[] { return [...this.tasks]; } addTask(title: string): void { const maxId = this.tasks.length > 0 ? Math.max(...this.tasks.map(t => t.id)) : 0; const newTask: Task = { id: maxId + 1, title, completed: false, }; this.tasks.push(newTask); this.saveTasks(); } deleteTask(id: number): void { this.tasks = this.tasks.filter(task => task.id !== id); this.saveTasks(); } toggleTask(id: number): void { const task = this.tasks.find(t => t.id === id); if (task) { task.completed = !task.completed; this.saveTasks(); } } }

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

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 5

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

course content

Contenido del Curso

Introduction to Angular

Introduction to Angular

1. Angular Fundamentals
2. Components and Templates
3. Mastering Angular Directives and Pipes
4. Services and Dependency Injection in Angular
5. Standalone Components & Modules
6. Routing and Navigation in Angular

book
Saving 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, we need to implement persistence using the browser's Local Storage. This means we 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:

ts

example

copy
123
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, we'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.

ts

example

copy
1234
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:

ts

example

copy
123
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:

ts

task-service

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
import { Injectable } from '@angular/core'; export interface Task { id: number; title: string; completed: boolean; } @Injectable({ providedIn: 'root' }) export class TaskService { private tasks: Task[] = []; constructor() { this.tasks = this.loadTasks(); } private saveTasks(): void { localStorage.setItem('tasks', JSON.stringify(this.tasks)); } private loadTasks(): Task[] { const data = localStorage.getItem('tasks'); return data ? JSON.parse(data) : []; } getTasks(): Task[] { return [...this.tasks]; } addTask(title: string): void { const maxId = this.tasks.length > 0 ? Math.max(...this.tasks.map(t => t.id)) : 0; const newTask: Task = { id: maxId + 1, title, completed: false, }; this.tasks.push(newTask); this.saveTasks(); } deleteTask(id: number): void { this.tasks = this.tasks.filter(task => task.id !== id); this.saveTasks(); } toggleTask(id: number): void { const task = this.tasks.find(t => t.id === id); if (task) { task.completed = !task.completed; this.saveTasks(); } } }

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

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 5
Lamentamos que algo salió mal. ¿Qué pasó?
some-alt