(精华2020年6月6日更新)Angular基础篇 服务services的使用

首先输入如下命令

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);
  }
}

app.module.ts注入

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');
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/106580991