Angular学习系列四:组件调用服务

基于上一篇内容,先打开vscode终端

1:创建服务: ng g service services/storage

2:数据双向绑定记得引用form moduler, 使用服务记得要引用服务,如下:

     在app.module.ts中,引入并配置服务: 

     import { StorageService } from './services/storage.service';   

     providers: [StorageService]
   
2: 具体组件引用具体服务
  比如先建todolist组件后,需要引入:import { StorageService } from '../../services/storage.service'; 并且在构造函数中注入该服务
 
3: 实现目标:组件调用服务,数据采用local storage持久化,初始ngOnInit生命周期
 
todolist 界面code:
 
 1 <p>todolist works!</p>
 2 <table>
 3     <tr>
 4         <td>
 5             <input type='text' [(ngModel)]="searchValue" />
 6             <button (click)="doSearch()">search</button>
 7         </td>
 8         <td>            
 9         </td>
10     </tr>
11     <tr>
12         <td>
13              搜索展示:
14         </td>
15         <td>
16             <ul>
17                 <li *ngFor="let item of historyList;let key = index;">
18                     {{item}}
19                     <button (click)="deleteHistory(key)">X</button>
20                 </li>
21             </ul>
22         </td>
23     </tr>
24     <tr>
25         <td>
26             按enter添加代办事项: <input type='text' [(ngModel)]="doValue" (keyup)="doAdd($event)"/>
27         </td>
28         <td>
29         </td>
30     </tr>
31     <tr>
32         <td>
33              代办事:
34              <ul>
35                 <li *ngFor="let item of doList;let key = index;" [hidden]="item.status">
36                     <input type="checkbox" [(ngModel)]="item.status"  (change)="changeStatus()">
37                     {{item.value}}
38                   <button (click)="deleteDo(key)">X</button>
39                 </li>
40             </ul>
41         </td>
42         <td>
43             已办事项:
44             <ul>
45                 <li *ngFor="let item of doList;let key = index;" [hidden]="!item.status">
46                     <input type="checkbox" [(ngModel)]="item.status" >
47                     {{item.value}}                  
48                 </li>
49             </ul>
50         </td>
51     </tr>
52 </table>
View Code

todolist typescript代码:

 1 import { Component, OnInit } from '@angular/core';
 2 
 3 //组件调用服务:
 4 import { StorageService } from '../../services/storage.service';
 5 
 6 //可以使用,但是不推荐
 7 //var storageObj = new StorageService();
 8 
 9 @Component({
10   selector: 'app-todolist',
11   templateUrl: './todolist.component.html',
12   styleUrls: ['./todolist.component.css']
13 })
14 export class TodolistComponent implements OnInit {
15 
16   public searchValue: string = "";
17   public historyList: any[] = [];
18 
19   public doValue: string = "";
20   public doList: any[] = [];
21   constructor(public storageObj: StorageService) {
22     //console.log(storageObj);
23 
24   }
25 
26   ngOnInit() {
27     console.log("每次页面刷新会触发该生命周期函数");
28     this.historyList = this.storageObj.get("searchList");
29     this.doList = this.storageObj.get("todoList");
30   }
31 
32   doSearch() {
33     if (this.historyList.indexOf(this.searchValue) == -1) {
34       this.historyList.push(this.searchValue);
35       this.storageObj.set("searchList", this.historyList);
36     }
37 
38     this.searchValue = "";
39     console.log(this.searchValue);
40   }
41 
42   deleteHistory(key) {
43     console.log(key);
44     this.historyList.splice(key, 1);//从key位置删除1个值
45     this.storageObj.set("searchList", this.historyList);
46   }
47 
48 
49 
50   doAdd(event) {
51     //console.log(event);
52     if (event.keyCode == 13) {
53       if (!this.todolistHasValue(this.doList, this.doValue)) {
54         this.doList.push({
55           value: this.doValue,
56           status: false,  //false:未做事 true:已完成
57         });
58         this.storageObj.set("todoList",this.doList);
59         this.doValue = "";
60       } else {
61         alert("数据存在");
62       }
63     }
64   }
65 
66   deleteDo(key) {
67     this.doList.splice(key, 1);
68     this.storageObj.set("todoList",this.doList);
69   }
70 
71   //判存
72   todolistHasValue(curdolist: any, curvalue: any) {
73 
74     for (var i = 0; i < curdolist.length; i++) {
75       if (curdolist[i].value == curvalue) {
76         return true;
77       }
78     }
79 
80     //异步,判存失败
81     // curdolist.forEach(ele => {
82     //   if (ele.value == curvalue) {
83     //     return true;
84     //   }
85     // });
86     return false;
87   }
88 
89   changeStatus(){
90     this.storageObj.set("todoList",this.doList);
91   }
92 }
View Code

storage服务代码:

 1 import { Injectable } from '@angular/core';
 2 
 3 @Injectable({
 4   providedIn: 'root'
 5 })
 6 export class StorageService {
 7 
 8   constructor() { }
 9 
10   set(key:string, value:any) {
11 
12     localStorage.setItem(key, JSON.stringify(value));
13   }
14 
15   get(key:string) {
16 
17     return JSON.parse(localStorage.getItem(key));
18   }
19   remove(key:string) {
20     localStorage.removeItem(key);
21   }
22 }
View Code

app.module.ts

 1 import { BrowserModule } from '@angular/platform-browser';
 2 import { NgModule } from '@angular/core';
 3 
 4 //引入表单组件才能双向绑定
 5 import {FormsModule} from '@angular/forms';
 6 
 7 //引入并配置服务
 8 import { StorageService } from './services/storage.service';
 9 
10 import { AppRoutingModule } from './app-routing.module';
11 import { AppComponent } from './app.component';
12 import { HeaderComponent } from './components/header/header.component';
13 import { FormComponent } from './components/form/form.component';
14 import { TodolistComponent } from './components/todolist/todolist.component';
15 
16 @NgModule({
17   //组件
18   declarations: [
19     AppComponent,
20     HeaderComponent,
21     FormComponent,
22     TodolistComponent
23   ],
24   //模块
25   imports: [
26     BrowserModule,
27     AppRoutingModule,
28     FormsModule
29   ],
30   //服务
31   providers: [StorageService],//配置
32   bootstrap: [AppComponent]
33 })
34 
35 
36 export class AppModule { }
View Code

界面效果图:

 

猜你喜欢

转载自www.cnblogs.com/hanliping/p/12150659.html