Angular中的服务 以及自定义服务

/*
1.创建服务:
ng g service services/storag

2.app.module.ts里面引入创建的服务并且声明。
import{StorageService} from "../../service/storage.service";
providers:[StorageService]

3.在用到的地方引入服务:
import{StorageService} from "../../service/storage.service";
初始化:
  constructor(public storage:StorageService) { 
    let s=this.storage.get();
    console.log(s);
  }

*/

storage.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  constructor() { }
  //设置服务:
  set(key:string,value:any){
    localStorage.setItem(key,JSON.stringify(value));
  }
  get(key){
    return JSON.parse(localStorage.getItem(key));
  }
  remove(key){
    localStorage.removeItem(key);
  }
}

使用:

import { Component, OnInit } from '@angular/core';

//引入服务:
import{StorageService} from "../../service/storage.service";


@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {

  constructor(public storage:StorageService) { 
    // let s=this.storage.get();
    // console.log(s);
  }

  ngOnInit() {
    console.log("页面刷新会触发这个生命周期函数");
    var searchlist=this.storage.get('searchlist');
    if(searchlist){
      this.historyList=searchlist;
    }
  }
  public keyword:string;
  public historyList:any[]=[];

  doSearch(){
    if(this.historyList.indexOf(this.keyword)==-1){
      this.historyList.push(this.keyword);
      this.storage.set('searchlist',this.historyList);
    }
    this.keyword=='';
    // console.log(this.keyword);
  }
  deleteHistroy(key){
    // alert(key);
    this.historyList.splice(key,1);
  }
}

原文地址:https://www.cnblogs.com/yiweiyihang/p/12147420.html