Angular之服務(service)

一 : 新建服務

ng g service  XXXX

B01.png


二 : 註冊服務

這裏和組件(component)不一樣需要手動註冊( 在app.module.ts中 )

B02.png


三 : 使用服務

① , 服務類  , 自己隨便寫點東西

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;

  }
}

② , 在組件中調用服務

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

注意 , 在構造函數中Angular引起會自動注入服務...

三 : 結果

B03.png



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章