提问者:小点点

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


我将按顺序列出待办事项。我使用本地存储来保存todo项目,但当我刷新数据时未显示,尽管数据保存在选项卡应用程序中。

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

这是stackBlitz链接:https://stackblitz.com/github/ntgiang4991/todo?file=src/app/components/todo-list/todo-list.component.ts

这是我的代码:filelocalstorage。服务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;
  }
}
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$;
}

文件待办事项列表。组成部分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个答案

匿名用户

试着把你的代码放在这里https://stackblitz.com/edit/angular-ivy-pphyej?embed=1

为了方便同事帮助你