Angular 5如何将json对象列表转换为列表

时间:2018-11-20 20:58:32

标签: angular

我正在使用Angular 5制作待办事项列表应用程序。 我能够将任务添加到具有本地存储的列表中。 但是我尝试在我的应用程序中包含多个列表,这意味着当用户单击下拉菜单时,用户可以选择任何列表,并查看该列表中的任务。

我将数据存储在JSON中(但是我不知道是否正确)。我认为我现在拥有的是JSON对象列表,但是我需要一个列表。

这是我的todo.service.ts

 import { Injectable } from '@angular/core';
 import { Todo } from '../classes/todo';

 @Injectable({
   providedIn: 'root'
 })
 export class TodoService {
   private todolist: Todo[];
   private nextId: number;


   constructor() {

     let todolist = this.getTodos();

     if (todolist.length == 0) {
       this.nextId = 0;
     } else {
       let maxId = todolist[todolist.length - 1].id;
       this.nextId = maxId + 1;
     }
   }

   public addTodo(text: string, date: Date): void {

     let jsonitem = new Todo(this.nextId,text,date);
     let todoitem = {      
       'id': jsonitem["nextId"],
       'text': jsonitem["text"],
       'date':jsonitem["date"]      
     };   

     let todolist = this.getTodos();   
     todolist.push(todoitem);
     this.setLocalStoragetodolist(todolist);
     this.nextId++;
   }

   public getTodos() :Todo[]{
     let localStorageItem = JSON.parse(localStorage.getItem('todolist'));
     return localStorageItem == null ? [] : localStorageItem.todolist; 
   }

   public removeTodo(id: number): void {
    let todolist = this.getTodos();
    todolist = todolist.filter((todoitem) => todoitem.id !== id);
    this.setLocalStoragetodolist(todolist);
   }

   private setLocalStoragetodolist(todolist: Todo[]): void {
    localStorage.setItem('todolist', JSON.stringify({todolist: todolist}));
   }
}

这是我的lists.component.ts

@Component({
  selector: 'app-lists',
  templateUrl: './lists.component.html',
  styleUrls: ['./lists.component.css']
})
export class ListsComponent implements OnInit {

  closeResult: string;
  // firstList: any;
  private todolist: Todo[];


  constructor(private modalService: NgbModal, private listService: ListService, private todoService: TodoService) {
    // this.getTodos();
  }

  ngOnInit() {
  }

  private getTodos(): void{
      this.todoService.getTodos();
  }
}

这是list.component.html

<div class="modal-body">
    <select [(ngModel)] = "todolist">
    <option value="" disabled selected>select a list</option>
</select>

0 个答案:

没有答案