zoukankan      html  css  js  c++  java
  • 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);
      }
    }

  • 相关阅读:
    WCF 第八章 安全 确定替代身份(中)使用AzMan认证
    WCF 第八章 安全 总结
    WCF 第八章 安全 因特网上的安全服务(下) 其他认证模式
    WCF Membership Provider
    WCF 第八章 安全 确定替代身份(下)模仿用户
    WCF 第八章 安全 因特网上的安全服务(上)
    WCF 第九章 诊断
    HTTPS的七个误解(转载)
    WCF 第八章 安全 日志和审计
    基于比较的排序算法集
  • 原文地址:https://www.cnblogs.com/yiweiyihang/p/12147420.html
Copyright © 2011-2022 走看看