我要去 Angular 的待办事项列表。我使用本地存储来保存待办事项,但是当我刷新数据时未显示,尽管数据保存在选项卡应用程序中。
这是火力基地链接:https ://gtodomvc.web.app/
这是 stackBlitz 链接:https ://stackblitz.com/github/ntgiang4991/todo?file=src%2Fapp%2Fcomponents%2Ftodo-list%2Ftodo-list.component.ts
这是我的代码:文件 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$)
}