ng g services 目录名
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
count: number = 1;
constructor() { }
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);
}
}
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';
import { StorageService } from './services/storage.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
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');
}
}