简体   繁体   English

刷新页面后LocalStorage不显示todolist数组

[英]LocalStorage not displaying array of todolist after refreshing page

I'm currently developing a ToDo List using Angular 8. When I enter in a task for my ToDo list it saves it in the Localstorage but when I refresh my page my tasks are gone but are still stored inside the localstorage of the browser.我目前正在使用 Angular 8 开发一个待办事项列表。当我为我的待办事项列表输入任务时,它会将其保存在 Localstorage 中,但是当我刷新页面时,我的任务消失了,但仍存储在浏览器的 localstorage 中。

How do I keep my tasks from disappearing after refreshing the browser, when they're still saved in LocalStorage?当我的任务仍然保存在 LocalStorage 中时,如何在刷新浏览器后防止它们消失?

import { Component, OnInit } from '@angular/core';
import { ToDo, IToDo } from './todo.model';
import { HttpClient } from '@angular/common/http';
import { LocalStorageService } from '../localStorageService';
import { ActivatedRoute, Router } from '@angular/router';
import { IUser } from '../login/login.component';
import { ToastService } from '../toast/toast.service';


@Component({
  // tslint:disable-next-line: component-selector
  selector: 'todolist',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class ToDoComponent implements OnInit {
  todos: Array<IToDo> = [];
  inputtask = "";
  toDoParams = '';
  localStorageService: LocalStorageService<IToDo>;
  currentUser: IUser;
  modal: any;
  constructor(
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
    private router: Router) {
    this.localStorageService = new LocalStorageService('todos');
  }



  private toastService: ToastService;
  async ngOnInit() {
    const currentUser = this.localStorageService.getItemsFromLocalStorage('user');
    console.log('from todos component', currentUser);
    if (currentUser == null) {
      this.router.navigate(['login']);
    }
  }





  // Creating a to do item by clicking on the Enter Button

  addToDo(todo: string) {
    const td = {
      id: 1,
      task: todo,
      editing: false
    }
    if (todo === '') {
      alert('You must enter in a task TO DO!')
    } else {
      this.todos.push(td);
    }
    this.saveItemsToLocalStorage(this.todos);
  }

  delete(index: number) {
    this.todos.splice(index, 1);
    console.log("index", index);
    this.saveItemsToLocalStorage(this.todos);
  }

  clear() {
    this.todos = [];
    console.log('index', this.todos)
    this.saveItemsToLocalStorage(this.todos);
  }

  getItemsFromLocalStorage(key: string) {
    const savedToDo = JSON.parse(localStorage.getItem(key));
    console.log('from getItemsFromLocalStorage savedItems', savedToDo);
    return this.localStorageService.getItemsFromLocalStorage(key);
    return savedToDo;
  }


  saveItemsToLocalStorage(todos: Array<IToDo>) {
    todos = this.sortByID(todos);
    return this.localStorageService.saveItemsToLocalStorage(todos);

    const savedToDo = localStorage.setItem('todos', JSON.stringify(todos));
    console.log('from saveItemsToLocalStorage savedToDos: ', savedToDo);
    return savedToDo;
  }

  sortByID(todos: Array<IToDo>) {
    todos.sort((prevToDo: IToDo, presToDo: IToDo) => {

      return prevToDo.id > presToDo.id ? 1 : -1;
    });
    console.log('the sorted ToDos', this.todos);
    return this.todos;
  }



  logout() {
    // clear localStorage
    this.localStorageService.clearItemFromLocalStorage();
    // navigate to login page
    this.router.navigate(['']);
  }
}

Here is the LocalStorageService file below这是下面的 LocalStorageService 文件

export class LocalStorageService<T> {
    constructor(private key: string) {

    }

    saveItemsToLocalStorage(todos: Array<T> | T) {
        const savedToDos = localStorage.setItem(this.key, JSON.stringify(todos));
        console.log('from saveItemsToLocalStorage savedToDos: ', savedToDos);
        return savedToDos;
    }
    getItemsFromLocalStorage(key?: string) {
        let savedItems;
        if (key != null) {
            const items = null;
            savedItems = JSON.parse(localStorage.getItem(key));
            console.log('from getItemFromLocalStorage key: ', key, 'savedItems: ', savedItems);
        } else {
            savedItems = JSON.parse(localStorage.getItem(this.key));

        }
        return savedItems;
    }

    clearItemFromLocalStorage(key?: string) {
        if (key != null) {
            const items = null;
            localStorage.setItem(key, JSON.stringify(items));
        } else {
            localStorage.clear();
        }
    }
}

Hey so when the page reloads angular loses context of the view so it has to render it again.嘿,所以当页面重新加载时,angular 会丢失视图的上下文,因此它必须再次渲染它。 You have all the working code here to make it work you just have to change the ngOnInit page load event so it reads them again and binds them to the property so angular can show them in the UI.您在这里拥有所有工作代码以使其工作,您只需要更改ngOnInit页面加载事件,以便它再次读取它们并将它们绑定到属性,以便 angular 可以在 UI 中显示它们。 Also bare in mind you call clearItemFromLocalStorage on logout so this won't grab them if they logout and then log back in, but i guess that was expected due to the code you have wrote.还请记住,您在注销时调用clearItemFromLocalStorage ,因此如果他们注销然后重新登录,这将不会抓住它们,但我想由于您编写的代码,这是预期的。

The below should slot in and work for you:下面应该插入并为您工作:

async ngOnInit() {
    const currentUser = this.localStorageService.getItemsFromLocalStorage('user');
    console.log('from todos component', currentUser);
    if (currentUser == null) {
      await this.router.navigate(['login']);
    } else {
      // if user is logged in go and find any items from local storage and bind 
      // to the view
      const toDoItems = this.localStorageService.getItemsFromLocalStorage('todos');
      if (toDoItems && Array.isArray(toDoItems)) {
         this.todos = toDoItems;
      }
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM