繁体   English   中英

Angular 2本地存储

[英]Angular 2 localstorage

我正在尝试在angular 2中使用localstorage 。我正在使用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 {}
}

暂无
暂无

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

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