Ng g services Directory nameCopy the code
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
// Provide a service that can be registered
export class StorageService {
  count: number = 1;

  constructor(){}// Write data to localStorage
  set(key: any, value: any) {
    localStorage.setItem(key, JSON.stringify(value))
  }
  //localStorage reads the data and converts it to a JSON object
  get(key: any) {
    return JSON.parse(localStorage.getItem(key));
  }
  // Delete the key value in localStorage
  remove(key: any) {
    localStorage.removeItem(key); }}Copy the code
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component'; / / the root component
import { StorageService } from './services/storage.service';
 

@NgModule({
  // Declare the component that is currently running the project
  declarations: [
    AppComponent
  ],
  // Import the currently running module
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  // Define the service
  providers: [StorageService],
  bootstrap: [AppComponent] // Boot the AppModule to start the application
})
export class AppModule {}Copy the code
import { Component, OnInit } from '@angular/core';
import {StorageService} from '.. /.. /services/storage.service';
@Component({
  selector: 'app-search'.templateUrl: './search.component.html'.styleUrls: ['./search.component.less']})export class SearchComponent implements OnInit {

  constructor(public storage:StorageService) { 

  }

  ngOnInit(): void {
    console.log(this.storage);
    var historys = this.storage.get('historyList'); }}Copy the code