我正在执行此操作,但是我不确定这是否是最好的解决方法。我觉得每种方法都应该有一种更简单的方法-addTodo,deleteTodoById,updateTodo。
我正在使用BehaviourSubject修改数组,但是在更新时,我希望消除用户输入(或延迟)并在后台更新本地存储
如何改善和简化RXJS代码?
import { Injectable } from "@angular/core"
import { Todo } from "./todo"
import { BehaviorSubject, Observable } from 'rxjs'
import { take } from 'rxjs/operators'
@Injectable()
export class TodoService {
todos: BehaviorSubject<Todo[]> = new BehaviorSubject<Todo[]>([]);
observable: Observable<Todo[]> = this.todos.asObservable();
getTodos(): Observable<Todo[]> {
try {
const todos: Todo[] = JSON.parse(localStorage.getItem('todos'))
if(!todos) {
return this.todos
}
this.todos.pipe(take(1)).subscribe(() => {
return this.todos.next(todos)
})
return this.todos;
} catch(err) {
console.log('have no local storage')
}
}
addTodo(todo: Todo): TodoService {
this.todos.pipe(take(1)).subscribe(todos => {
this.updateLocalStorage([...todos, todo])
return this.todos.next([...todos, todo])
})
return this
}
deleteTodoById(id): TodoService {
this.todos.pipe(take(1)).subscribe(todos => {
const filteredTodos = todos.filter(t => t.id !== id)
this.updateLocalStorage(filteredTodos)
return this.todos.next(filteredTodos)
})
return this
}
updateTodo(id, title): void {
this.todos.pipe(take(1)).subscribe((todos) => {
const todo = todos.find(t => t.id === id)
if(todo) {
todo.title = title
const newTodos = todos.map(t => (t.id === id ? todo : t))
this.updateLocalStorage(newTodos)
return this.todos.next(newTodos)
}
})
}
updateLocalStorage(todos):void {
this.todos.subscribe(t => {
setTimeout(() => {
localStorage.setItem('todos', JSON.stringify(todos))
}, 300)
})
}
}
答案 0 :(得分:1)
到目前为止,我不确定您要改进什么。
我已经创建了这个伪造的应用程序,向您展示了我如何管理这种操作。
在此应用程序上,我没有使用Angular的ReactiveFormModule
,它可以很容易地提取这部分内容:
const inputElement = document.getElementById('input') as HTMLInputElement;
const onChange$ = fromEvent(
inputElement, // In keyup from input field.
'keyup'
).pipe(
debounceTime(1000), // Delay the user input
map(() => inputElement.value) // Transform KeyboardEvent to input value string.
);
通过做这样的事情
<input
type="text"
name="title"
[formControl]="title"
>
export class FooComponent implement OnInit {
title: FormControl = new FormControl();
ngOnInit() {
this.title.valueChanges.pipe(debounceTime(1000)).subscribe(title => {
// Do something with your debounced data.
})
}
}
然后您可以遵循以下逻辑:
export class TodoService {
private _todos$: BehaviorSubject<Todo[]>;
private _todos: Todo[];
constructor() {
this._todos = (this.hasLocalStorage())?this.getLocalStorage():[];
this._todos$ = new BehaviorSubject(this._todos);
}
add(todo: Todo) {
this._todos.push(todo);
this.refresh();
}
edit(id: number, title: string) {
// Find by id and copy current todo.
const todo = {
...this._todos.find(todo => todo.id === id)
};
// Update title
todo.title = title;
// Update todos reference
this._todos = [
// Find any other todos.
...this._todos.filter(todo => todo.id !== id),
todo
];
this.refresh();
}
get todos$(): Observable<Todo[]> {
return this._todos$.asObservable();
}
private refresh() {
this._todos$.next([...this._todos]);
localStorage.setItem('todos', JSON.stringify(this._todos));
}
private hasLocalStorage(): boolean {
return (localStorage.getItem('todos') !== null);
}
private getLocalStorage(): Todo[] {
return JSON.parse(localStorage.getItem('todos'));
}
}
1 /这里我有2个属性,一个是我的商店,我将始终引用我的所有待办事项,第二个是我的BehaviorSubject,用于在商店更新时通知我的应用程序的其余部分。
2 /在我的构造函数中,我通过空数组或localStorage数据(如果存在)来初始化两个属性。
3 /我有refresh
方法,可做两件事,同时更新两个属性。
4 /在添加/编辑/删除操作中,我将其作为常规数组操作执行,然后称为“刷新”。
瞧瞧