数据保存在本地存储中,但刷新时不显示

时间:2020-06-12 08:38:23

标签: angular local-storage todomvc

我要按Angular进入待办事项列表。我使用本地存储来保存待办事项,但刷新数据时未显示,尽管数据保存在选项卡应用程序中。

这是Firebase链接:https://gtodomvc.web.app/

这是stackBlitz链接:https://stackblitz.com/github/ntgiang4991/todo?file=src%2Fapp%2Fcomponents%2Ftodo-list%2Ftodo-list.component.ts

the data in local storage

这是我的代码: 文件localstorage.service.ts

export class LocalStorageService {
  storage: Storage;

  constructor() { 
    this.storage = window.localStorage
  }

  set(key: string, value: string): void{
    this.storage[key] = value;
  }

  get(key: string): string{
    return this.storage[key] || false;
  }

  setObject(key: string, value: any): void{
    if(!value){
      return;
    }
    this.storage[key] = JSON.stringify(value);
  }

  getValue<T>(key: string): T{
    const obj = JSON.parse(this.storage[key] || null);
    return <T>obj || null;
  }
}

文件todo.service.ts

private todos: Todo[] = [];
todos$: Observable<Todo[]> = this.displayTodosSubject.asObservable();

fetchFromLocalStorage(){
    this.todos = this.storageService.getValue<Todo[]>(TodoService.TodoStorageKey) || [];
}

文件todo-list.component.ts

todos$: Observable<Todo[]>;
ngOnInit(): void {
    this.todos$ = this.todoService.todos$;
}

文件todo-list.component.html

<app-todo-item *ngFor="let todo of todos$ | async" [todo]="todo" 
    (changeStatus)="onChangeTodoStatus($event)" 
    (editTodo)="onEditTodo($event)" 
    (deleteTodo)="onDeleteTodo($event)"
>
</app-todo-item>

文件app.component.ts

ngOninit(){
    this.todoService.fetchFromLocalStorage();

    this.hasTodo$ = this.todoService.length$.pipe(map(length => length > 0));
    console.log(this.todoService.length$)
}

1 个答案:

答案 0 :(得分:0)

尝试将您的代码放入此 https://stackblitz.com/edit/angular-ivy-pphyej?embed=1&file=src/app/app.component.ts

使同事更轻松地为您提供帮助