1. 程式人生 > >angularcli 第七篇(service 服務)

angularcli 第七篇(service 服務)

div inf stringify splice angular value mod struct 頁面

在組件中定義的信息是固定的,假設另外一個組件也需要用到這些信息,這時候就用到服務,實現數據共享

技術分享圖片

1、創建服務到指定目錄下:

  • ng g service services / storage

技術分享圖片

2、app.module.ts裏面引入創建的服務

  • import { StorageService } from ‘. /service / storage.service‘;
  • @NgModule裏面的providers依賴註入服務 provides: [ StorageService ] ,

技術分享圖片

3、使用的頁面引入服務、註冊服務

  • import { StorageService } from ‘../. /service / storage.service‘;
  • private storage : StorageService 註入到構造函數

技術分享圖片

到這裏todolist 組件就可以使用 storage.service 服務裏的數據了

todolist.component.ts界面:

export class TodolistComponent implements OnInit {

  public username:any=‘‘;
  public list=[];

  //private storage:StorageService  依賴註入服務
  constructor(private storage:StorageService
) { console.log(
this.storage); // this.storage.setItem(‘username‘,‘張三‘); // alert(this.storage.getItem(‘username‘)); } ngOnInit() { //每次刷新獲取storage裏面 todolist的值 var todolist=this.storage.getItem(‘todolist‘); if(todolist){ this.list=todolist; } } addData(e){
//1.從storage獲取 todolist的數據 //2.如果有數據,拿到這個數據,然後把新數據和這個storage數據拼接,重新寫入 //3.如果沒有數據 直接給storage寫入數據 if(e.keyCode==13){ var obj={ /*每次增加的一個對象數據*/ username:this.username, status:1 } var todolist=this.storage.getItem(‘todolist‘); if(todolist){ todolist.push(obj); //如果有數據,拿到這個數據,然後把新數據和這個storage數據拼接,重新寫入 this.storage.setItem(‘todolist‘,todolist); }else{ //3.如果沒有數據 直接給storage寫入數據 var arr=[]; arr.push(obj); this.storage.setItem(‘todolist‘,arr); } this.list.push(obj); this.username=‘‘; } // console.log(e); } deleteData(key){ // alert(key); this.list.splice(key,1); /*刪除數組的數據*/ } changeData(key,status){ /*改變狀態*/ this.list[key].status=status; this.storage.setItem(‘todolist‘,this.list); } }

Storage.Service.ts界面:

export class StorageService {

  constructor() {   /*構造函數*/
  }

  setItem(key,value){
      localStorage.setItem(key,JSON.stringify(value))
  }

  getItem(key){
      return JSON.parse(localStorage.getItem(key));
  }

  removeItem(key){
    localStorage.removeItem(key);
  }
}

angularcli 第七篇(service 服務)