文章16 | 阅读 6585 | 点赞0
ng g services 目录名
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
//提供一个可以注册的服务
export class StorageService {
count: number = 1;
constructor() { }
//将数据写入localStorage
set(key: any, value: any) {
localStorage.setItem(key, JSON.stringify(value))
}
//localStorage读取数据,转化为json对象
get(key: any) {
return JSON.parse(localStorage.getItem(key));
}
// localStorage中删除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] //引导AppModule来启动应用
})
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');
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://codeboy.blog.csdn.net/article/details/107801815
内容来源于网络,如有侵权,请联系作者删除!