javascript - Angular 2 本地存储

标签 javascript html angular local-storage

我正在尝试在 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检查>应用程序>本地存储中我看到了数据。当我重新加载页面时,数据仍然会出现,但不会出现在 View 中,当我添加新的待办事项时,本地存储会删除旧项目并使用新的待办事项进行更新。

有谁知道怎么解决吗?

最佳答案

像这样使用你的代码

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 变量

关于javascript - Angular 2 本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42787225/

相关文章:

javascript - 动态显示和初始化多个谷歌地图

javascript - 关于webrtc中使用socket,io进行socket连接

javascript - 除了 .innerHTML 之外,还有哪些其他选项可以将 Javascript 生成的 HTML 插入 DOM?

angular - 我想知道如何使用 textarea 在 Angular 中建模

angularjs - 我们可以使用 Ionic 2 和 AngularJs 1 吗?

javascript - 当另一个数据更新时,Angular 2更新数据

javascript - 隐藏 slider 中具有相同 id 的空图像

javascript - get/src/components/App.jsx : Unexpected token, 预期 "}"onClick 事件错误

html - 无法将表格布局转换为 DIV

php - 编码奇数 HTML 实体 '&lstroke;'