在angular中实现服务,用本地存储,刷新以后数据还在
步骤一、命令行输入------表示在app文件夹下新建一个services文件夹,里面放服务(storage)
ng g service services/storage
步骤二、在根组件的modules.ts引入服务
可以直接复制以下内容到app.module.ts相应位置
//引入服务
import { StorageService } from './services/storage.service.ts'
//声明服务
providers: [StorageService],
步骤三、在要使用的组件中引入服务
import { StorageService } from "../../services/storage.service.ts";
并且在构造函数中初始化
// 初始化服务
constructor(public storage:StorageService) {
}
现在可以在当前组件中使用StorageService中的方法或者属性
使用本地存储
步骤四、在前面新建的storage.service.ts中定义本地存储的方法
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
set(key:string,value:any){
localStorage.setItem(key,JSON.stringify(value))
return 1
}
get(key:string){
return JSON.parse(localStorage.getItem(key))
}
remove(key:string){
localStorage.removeItem(key)
}
}
组件中使用
demo示例
最终效果
项目结构如下
首先、我们先看根组件部分
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// 引入其他组件
import { NewsComponent } from './components/news/news.component';
import { MainComponent } from './components/main/main.component';
// 引入服务
import { StorageService } from './services/storage.service'
@NgModule({
declarations: [
AppComponent,
NewsComponent,
MainComponent
],
imports: [
BrowserModule,
FormsModule
],
// 声明服务
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<!-- 模仿京东搜索todolist -->
<app-main ></app-main>
app.component.css,暂时没写样式,所以不展示了
app.component.ts 和 app.component.spec.ts 脚手架搭建好就没改过,所以也不展示
然后是服务部分
因为命令行输入服务命令后自动生成这两个文件,storage.service.spec.ts没改过,不展示了,下面只展示storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
set(key:string,value:any){
localStorage.setItem(key,JSON.stringify(value))
return 1
}
get(key:string){
return JSON.parse(localStorage.getItem(key))
}
remove(key:string){
localStorage.removeItem(key)
}
}
然后是父组件main
没写样式,所以main.component.css为空,不展示,main.component.spec.ts也是命令行新建组件自动生成就没改过,也不展示
main.component.html
<hr>
<div>
我是子组件
<app-news #childState></app-news>
</div>
<hr>
<button (click)='getChild()'>点击我获取子组件的标题</button>
<span>{{childS}}</span>
<div>我是父组件toDoList</div>
<div>
<label for="serchSth">请输入搜索内容</label>
<input
type="text"
id="serchSth"
[(ngModel)]="serchState"
(keyup)="search($event)"
/>
</div>
<div>
<h2>未完成</h2>
<p *ngFor="let item of toDoList; let key = index" [hidden]="item.checked">
<input
type="checkbox"
name="checkItem"
id="checkItem"
[(ngModel)]="item.checked"
(change)="change()"
/>{{ item.name }} <button (click)="deleteItem(key)">X</button>
</p>
</div>
<div>
<h2>已完成</h2>
<p *ngFor="let item of toDoList; let key = index" [hidden]="!item.checked">
<input
type="checkbox"
name="checkItem"
id="checkItem"
[(ngModel)]="item.checked"
/>{{ item.name }} <button (click)="deleteItem(key)">X</button>
</p>
</div>
main.component.ts
import { Component, OnInit, ViewChild } from "@angular/core";
// 引入服务
import { StorageService } from "../../services/storage.service";
@Component({
selector: "app-main",
templateUrl: "./main.component.html",
styleUrls: ["./main.component.css"]
})
export class MainComponent implements OnInit {
// 父子组件传值,使用viewchild方法
@ViewChild('childState',{static:true}) childState: any;
public childS:string;
public serchState: string;
public toDoList: any[] = [];
/**
* name
*/
public search(e) {
if (e.keyCode == 13) {
let isRepeat = this.isRepeat(this.toDoList, this.serchState);
if (!isRepeat) {
this.toDoList.push({
name: this.serchState,
checked: false
});
this.storage.set("toDoList",this.toDoList)
} else {
alert('数据重复');
}
this.serchState = "";
}
}
// 初始化服务
constructor(public storage:StorageService) {
}
ngOnInit() {
let toDoList = this.storage.get('toDoList')
if (toDoList) {
this.toDoList = toDoList
}
}
// 删除当前选项
deleteItem(key) {
this.toDoList.splice(key, 1);
this.storage.set("toDoList",this.toDoList)
}
// 判断重复
isRepeat(arrList: any, key: string): any {
for (const item of arrList) {
if (item.name == key) {
return true;
}
}
return false;
}
//输入框改变事件
change(){
this.storage.set("toDoList",this.toDoList)
}
//父子组件传值
getChild(){
console.log(this.childState.tittle)
this.childS = this.childState.tittle
}
}
然后是子组件
跟父组件一样,不展示css和spect.ts
news.component.html
<div>
{{tittle}}
</div>
news.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
public tittle = '信息采集'
constructor() { }
ngOnInit() {
}
}