Angular 2 个本地存储

Angular 2 localstorage

我正尝试在 angular 中使用 localstorage 2。我正在使用 angular cli

app.component.ts

export class AppComponent implements OnInit {
    currentItem: string;
    newTodo: string;
    todos: any;

    constructor(){
        this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [  ];
        localStorage.setItem('currentItem', JSON.stringify(this.currentItem));
        this.newTodo = '';
        this.todos = [];
    }

    addTodo() {
        this.todos.push({
            newTodo: this.newTodo,
            done: false
        });
        this.newTodo = '';
        localStorage.setItem('currentItem', JSON.stringify(this.todos));

    }

    ngOnInit(): void {}
}

app.component.html

 <div>
    <form (submit)="addTodo()">
        <label>Name:</label>
        <input [(ngModel)]="newTodo" class="textfield" name="newTodo">
        <button  type="submit">Add Todo</button>
    </form>
</div>

<ul class="heroes">
    <li *ngFor="let todo of todos; let i=index ">
        <input type="checkbox" class="checkbox" [(ngModel)]="todo.done" />
        <span [ngClass]="{'checked': todo.done}">{{ todo.newTodo }}</span>
        <span (click)="deleteTodo(i)" class="delete-icon">x</span>
    </li>
</ul>

<div>
    <button (click)="deleteSelectedTodos()">Delete Selected</button>
</div>

这是一个简单的待办事项列表,但它不会在我重新加载页面时保留数据。

在chrome inspect > Application > Local Storage 我看到了数据。当我重新加载页面时,数据仍然出现,但它没有出现在视图中,当我添加新的待办事项时,本地存储删除旧项目并更新为新的待办事项。

有人知道怎么解决吗?

像这样使用你的代码

constructor(){
    this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [  ];
    this.todos = this.currentItem;
}

addTodo() {
    let local_items = localStorage.getItem('currentItem')
    local_items.push({
        newTodo: this.newTodo,
        done: false
    });
    localStorage.setItem('currentItem', JSON.stringify(local_items));
    this.newTodo = '';
}

原因:

  • 在添加时,您在 localStorage 中设置了数组,其中只有最新对象没有旧对象。
  • 在刷新页面时,您没有将 localStorage 对象分配给 todo 变量

我稍微修改了为 Pardeep Jain 提供的代码,然后醒了!

export class AppComponent implements OnInit {

    currentItem: string;
    newTodo: string;
    todos: any;

    constructor(){
        this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [  ];
        this.todos = this.currentItem;
    }

    addTodo() {
        this.todos.push({
            newTodo: this.newTodo,
            done: false
        });
        this.newTodo = '';
        localStorage.setItem('currentItem', JSON.stringify(this.todos));
    }

    ngOnInit(): void {}
}