刷新页面后LocalStorage不显示待办事项数组

时间:2019-11-24 22:07:48

标签: javascript angular typescript web-applications local-storage

我当前正在使用Angular 8开发待办事项列表。当我为待办事项列表输入任务时,它将其保存在Localstorage中,但是当我刷新页面时,我的任务已消失,但仍存储在该任务的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(['']);
  }
}

这是下面的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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

嘿,所以当页面重新加载angular时,它会丢失视图的上下文,因此必须再次呈现它。您这里拥有所有有效的代码,只需更改ngOnInit页面加载事件即可,使其再次读取它们并将其绑定到属性,以便angular可以在UI中显示它们。另外请记住,您在注销时调用clearItemFromLocalStorage,因此如果他们注销然后重新登录,这将不会抓住他们,但是我想这是您编写的代码所期望的。

以下内容应插入并为您工作:

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;
      }
    }
  }