學習angular4.x中的服務須要藉助 ToDoList 項目來作,項目代碼在上篇博客中講到。css
把多個組件共同的功能編寫爲一個服務,當組件須要使用公共的功能時,只須要把服務引用,就能夠使用服務中的屬性和方法。git
https://github.com/angular/angular-cligithub
爲了方便項目的管理和維護,咱們單首創建一個 services 文件夾用於存放咱們建立的服務(相似於以前存放自定義組件的components文件夾)。數組
ng g service services/storage
建立出了服務。bash
import { StorageService } from './services/storage.service';
import { StorageService } from '../../services/storage.service';
方法一:(官方不推薦使用)app
public storage = new StorageService(); /**能夠引入和使用服務 */
方法二:(官方推薦)angular4
// private storage:StorageService 依賴注入服務 constructor(private storage:StorageService) { this.username = ''; }
storage.service.ts 文件ide
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) 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); } }
todolist.component.ts 文件函數
import { Component, OnInit } from '@angular/core'; import { StorageService } from '../../services/storage.service'; @Component({ selector: 'app-todolist', templateUrl: './todolist.component.html', styleUrls: ['./todolist.component.css'] }) export class TodolistComponent implements OnInit { public username: any; public list = []; // public storage = new StorageService(); /**能夠引入和使用服務 */ // private storage:StorageService 依賴注入服務 constructor(private storage: StorageService) { this.username = ''; } ngOnInit() { // // 每次刷新獲取 todolist var todolist = this.storage.getItem('todolist') if(todolist){ // 判斷是否是空 this.list = todolist } } addData(e) { // 添加數據 // 檢測是否按回車 if (e.keyCode == 13) { var obj = { /***每次增長的一個對象數據 */ username: this.username, status: 1 } // 1. 從storage中獲取數據,todolist的數據 var todolist = this.storage.getItem('todolist') // 2. 若是有數據,拿到這個數據而後把新數據和這個數據拼接,從新寫入。 if (todolist) { todolist.push(obj) this.storage.setItem('todolist', todolist) } else { // 3. 若是沒有數據,直接給storage寫入數據 var arr = []; arr.push(obj) this.storage.setItem('todolist', arr) } this.list.push(obj) this.username = '' } } deleteData(key) { // 刪除數據 傳進索引值 this.list.splice(key, 1) /**刪除數組的數據:從key索引開始刪除,刪除一個數據 */ this.storage.setItem('todolist',this.list) } changeData(key,status) { // 改變狀態 this.list[key].status = status this.storage.setItem('todolist',this.list) } }
todolist.component.html 文件
<br> <br> <input type="text" [(ngModel)]='username' (keydown)='addData($event)'> <hr> <h2>正在進行</h2> <ul> <li *ngFor="let item of list;let i = index;" [hidden]="item.status==2"> <button (click)="changeData(i,2)">改變數據</button> {{item.username}} --------- <button (click)="deleteData(i)">刪除</button> </li> </ul> <h2>已經完成</h2> <ul> <li *ngFor="let item of list;let i = index;" [hidden]="item.status==1"> <button (click)="changeData(i,1)">改變數據</button> {{item.username}} --------- <button (click)="deleteData(i)">刪除</button> </li> </ul>