📅  最后修改于: 2023-12-03 15:32:44.171000             🧑  作者: Mango
LocalStorage is a popular way to store data in the browser. It is a key-value pair storage mechanism that allows developers to store simple data in the browser. The getItem method is used to retrieve the value associated with a specified key from LocalStorage. In this tutorial, we will learn how to get an item from LocalStorage in Angular using TypeScript.
Create a new Angular application using the following command:
ng new localstorage-getitem-angular
Add a new component using the following command:
ng generate component local-storage
Add the following code to the component's .ts file:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-local-storage',
templateUrl: './local-storage.component.html',
styleUrls: ['./local-storage.component.css']
})
export class LocalStorageComponent implements OnInit {
data: string;
constructor() {}
ngOnInit() {
this.data = localStorage.getItem('key');
}
}
The code above imports the necessary modules needed to create a component in Angular. It declares a data
variable and initializes it to the value returned from the getItem method of LocalStorage. This value is set using a key key
which is passed as an argument to the getItem method.
The ngOnInit
method is a lifecycle hook that is called when the component is created. Here, we use it to get the data from LocalStorage and update the data
variable.
Add the following code to the component's .html file:
<p>Data from LocalStorage: {{ data }}</p>
This code will display the value of the data
variable as retrieved from LocalStorage.
Run the following command to start the application:
ng serve
Open your browser and navigate to http://localhost:4200. You should see the message "Data from LocalStorage: null". This is because there is no value associated with the key key
in LocalStorage. To test the code, set a value for the key key
in LocalStorage using the following code:
localStorage.setItem('key', 'Hello World');
Refresh the browser and you should see the message "Data from LocalStorage: Hello World".
In this tutorial, we learned how to use the getItem method of LocalStorage to get data from the browser's storage mechanism. We also learned how to create an Angular component and display the result. With this knowledge, you can now retrieve data from LocalStorage in your Angular applications using TypeScript.