(精华)2020年8月4日 Angular 服务services的使用

x33g5p2x  于2022-03-06 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(376)
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');
  }
}

相关文章