Angular 2 localstorage

时间:2017-03-14 13:23:29

标签: javascript html5 angular local-storage

我正在尝试使用角度为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检查中&gt;申请&gt;本地存储我看到了数据。当我重新加载页面时,数据仍会显示,但它不会出现在视图中,当我添加新的待办事项时,本地存储会删除旧项目并使用新的待办事项进行更新。

有谁知道如何修复它?

2 个答案:

答案 0 :(得分:1)

像这样使用你的代码

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中添加set数组时,只有最新的对象而不是旧对象。
  • 在刷新页面上,您没有将localStorage对象分配给todo变量

答案 1 :(得分:1)

我修改了为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 {}
}