angular7实现todolist功能(本地存储、服务)

使用angular服务、本地存储实现todolist

服务的创建与使用:

创建服务

ng g s services/storage	

服务的配置:在app.module.ts中引入并声明

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

providers: [StorageService]

使用:在使用的组件的ts中引入并使用

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

constructor(public storage: StorageService) { // 获取服务的实例
    let serverGet = storage.get();
    console.log(serverGet)
}

html:


待办事项:

  • { {item.title}} -----------

已完成事项:

  • { {item.title}} -----------
  • ts:

    import { Component, OnInit } from '@angular/core';
    import { StorageService } from 'src/app/services/storage.service';
    
    @Component({
      selector: 'app-todolist',
      templateUrl: './todolist.component.html',
      styleUrls: ['./todolist.component.styl']
    })
    export class TodolistComponent implements OnInit {
    
      public keyword: string;
      public todolist: any[] = [];
    
      constructor(public storage: StorageService) {
        
      }
    
      ngOnInit() {
        let todolist: any = this.storage.get("todolist");
        if(todolist) {
          this.todolist = todolist;
        }
      }
    
      doAdd(e) {
        if (e.keyCode == 13) {
          if(!this.todolistHasKeyword(this.todolist, this.keyword)) {
            this.todolist.push({
              title: this.keyword,
              status: 0 // 0表示待办事项,1表示已完成事项
            });
            this.keyword = '';
            this.storage.set("todolist", this.todolist);
          }else {
            alert("数据已存在!");
          }
        }
      }
    
      checkBoxChange() {
        console.log('tag', '')
      }
    
      deleteData(index) {
        this.todolist.splice(index, 1);
        this.storage.set("todolist", this.todolist);
      }
    
      todolistHasKeyword(todolist: any, keyword: any) {
        // 异步会存在问题
        // todolist.forEach(value => {
        //   if(value.title == keyword) {
        //     return true;
        //   }
        // });
        if(!keyword) return false;
        for(var i = 0 ; i < todolist.length ; i++) {
          if(todolist[i].title == keyword) {
            return true;
          }
        }
        return false;
      }
    }
    
    

    services:

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class StorageService {
    
      constructor() { }
    
      set(key: string, value: any) {
        localStorage.setItem(key, JSON.stringify(value));
      }
    
      get(key: string) {
        return JSON.parse(localStorage.getItem(key));
      }
    
      remove(key: string) {
        localStorage.removeItem(key);
      }
    
    }
    
    

    效果:
    angular7实现todolist功能(本地存储、服务)_第1张图片

    你可能感兴趣的:(angular,angular,服务,localhostorage,services)