- Crear un servicio
ng g service service/storage
- La introducción de servicios creada en app.module.ts y declarar
import { StorageService } from './service/storage.service';
providers: [StorageService], /*配置项目所需要的服务 */
- Introducción de los componentes utilizados en el interior
import { StorageService } from './service/storage.service';
providers: [StorageService], /*配置项目所需要的服务 */
// 初始化
constructor(public storage: StorageService) {
console.log(this.storage.get());
}
- localStorage paquete
set(key: any, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
get(key: any) {
return JSON.parse(localStorage.getItem(key));
}
remove(key: any) {
localStorage.removeItem(key);
}
por ejemplo
Nota: Esta función ngOnInit introducir un ciclo de vida para todo el mundo :( actualización de la página hará que la función del ciclo de vida)
<div class="search_box">
<input type="text" placeholder="请输入……" [(ngModel)]="keyWord" (keyup)="keyUpFn($event)">
<hr>
<p>待办事件</p>
<div class="search_list" *ngFor="let item of historyList;let key=index" [hidden]="item.status==1">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkedChange()"> {{item.title}} <button (click)="delete(key)">X</button>
</div>
<p>已完成事件</p>
<div class="search_list" *ngFor="let item of historyList;let key=index" [hidden]="item.status==0">
<input type="checkbox" [(ngModel)]="item.status" (change)="checkedChange()"> {{item.title}} <button (click)="delete(key)">X</button>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import {StorageService} from '../service/storage.service';
@Component({
selector: 'app-to-dolist',
templateUrl: './to-dolist.component.html',
styleUrls: ['./to-dolist.component.scss']
})
export class ToDolistComponent implements OnInit {
public keyWord: string;
public historyList: any[] = [];
constructor(public storage: StorageService) {
console.log(this.storage.get());
}
ngOnInit() {
console.log('页面刷新会触发这个生命周期函数');
const searchList: any = this.storage.get('searchlist');
if (searchList) {
this.historyList = searchList;
}
}
// 键盘事件
keyUpFn(e) {
if (e.keyCode == 13) {
if (this.historyList.indexOf(this.keyWord) == -1) {
this.historyList.push({
title: this.keyWord,
status: false
});
}
this.keyWord = '';
this.storage.set('searchlist', this.historyList);
}
}
// 删除信息事件
delete(key) {
this.historyList.splice(key, 1);
this.storage.set('searchlist', this.historyList);
}
// 监听状态
checkedChange() {
console.log('事件触发了');
this.storage.set('searchlist', this.historyList);
}
}
- Angulares todos los componentes pueden ser llamadas de servicio, no hay manera de llamar al componente de servicio, el componente hay manera de llamar al método de montaje, podemos llamar a los demás entre los servicios y servicio.