1,创建服务
2,使用服务
// 引入服务 import { StorageService } from ‘./services/storage.service‘ // 配置服务 @NgModule({ providers: [StorageService], // 配置项目所需要的服务 })
import { Injectable } from ‘@angular/core‘; @Injectable({ providedIn: ‘root‘ }) export class StorageService { constructor() { } // 定义方法 set() { // 存储 window.localStorage.setItem(‘变量名‘, JSON.stringify(变量值)); } get() { // 获取 window.localStorage.getItem(‘变量名‘); } remove() { // 删除 window.localStorage.removeItem(‘变量名‘); } }
import { StorageService } from ‘../../services/storage.service‘ constructor(public storage: StorageService) { this.storage.set(); // 调用服务中的设置本地缓存数据的方法 this.storage.get(); // 调用服务中的获取本地缓存数据的方法 this.storage.remove(); // 调用服务中的删除本地缓存数据的方法 }
原文:https://www.cnblogs.com/zxuedong/p/12534662.html