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

  • 相关阅读:
    DM逻辑结构
    DM常见问题
    DM进程与线程
    DM物理存储结构
    systemdlogind.service的RemoveIPC参数影响
    DM内存结构
    DMSQL记录日志跟踪功能
    ACM中java的使用
    Java读取CSV文件为List
    Vue打包优化 优化JS过大 西门
  • 原文地址:https://www.cnblogs.com/yiweiyihang/p/12147420.html
Copyright © 2020-2023  润新知