A: New Service

g service XXXX

B01.png


II: Registration Service

Here and components (component) is not the same need to manually register (in app.module.ts in)

B02.png


3: Use Service

①, service class, just write something yourself

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

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

  constructor() {}
  public setLocal<DATA>( $key : string , $data : DATA ) : void{
      localStorage.setItem( $key , typeof($data) === "string" ? $data : JSON.stringify($data) );
  }
  public getLocal<DATA>( $key : string ) : DATA{
     let $data : string = localStorage.getItem( $key );
     return  JSON.parse( $data ) as DATA;

  }
}

②, call the service in the assembly

import { Component, OnInit } from '@angular/core';
import { UserVo } from 'src/app/demo/UserVo';
import {EventMessage} from "../../lib/EventMessage";
import {NewsService} from '../../services/news.service';

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

  ngOnInit() {
  }

  public  constructor( public _newService : NewsService ){
    let $arr : Array<string> = [
      "Array",
      "[]"
    ];
    this._newService.setLocal<Array<string>>( "user" , $arr );

    let $a : Array<string>  = this._newService.getLocal<Array<string>>( "user" );
    //console.log( $a );
  }
}

Note that in the constructor will be automatically injected into the cause Angular service ...

Three: results

B03.png