Arrays 将元素添加到数组时触发集()
我正在尝试管理角度服务中的阵列,如下所示:Arrays 将元素添加到数组时触发集(),arrays,angular,typescript,Arrays,Angular,Typescript,我正在尝试管理角度服务中的阵列,如下所示: import { TodoItem } from '../models/todo-item.model'; @Injectable() export class TodoService { //local storage key name private readonly lsKey = 'pi-todo'; private _todos: Array<TodoItem>; //Gets the todo items f
import { TodoItem } from '../models/todo-item.model';
@Injectable()
export class TodoService {
//local storage key name
private readonly lsKey = 'pi-todo';
private _todos: Array<TodoItem>;
//Gets the todo items from local storage
public fetchTodos(): Array<TodoItem> {
//Either get the items if they exist, or get an empty array
this.todos = (JSON.parse(localStorage.getItem(this.lsKey)) as Array<TodoItem>) || [];
return this.todos;
}
//Adds the todo item to local storage
public addTodo(todo: TodoItem): Array<TodoItem> {
if (todo) {
//Better way to do this?
let tempTodos = this.todos;
tempTodos.push(
Object.assign(
{
completed: false
},
todo
)
);
this.todos = tempTodos;
return this.todos;
}
}
private get todos(): Array<TodoItem> {
return this._todos || [];
}
private set todos(todos: Array<TodoItem>) {
this._todos = todos;
localStorage.setItem(this.lsKey, JSON.stringify(this._todos));
}
}
将todo项添加到todos数组时,我尝试了这样做。todos.push。。。;但这不会触发二传手。如何在不使用临时数组的情况下执行此操作?是的,因为您没有将其设置为新值。一种解决方法是:不要将其推入数组,而是获取当前数组,将其分配给临时变量,然后替换为新数组。像这样:
triggerSet(newValue) {
const tempArray = this.todos;
tempArray.push(newValue);
this.todos = tempArray;
}
我建议将save-to-local存储代码移动到setter和add调用的单独方法中
//Adds the todo item to local storage
public addTodo(todo: TodoItem): Array<TodoItem> {
if (todo) {
this.todos.push(
Object.assign(
{
completed: false
},
todo
)
);
this.save();
return this.todos;
}
}
private set todos(todos: Array<TodoItem>) {
this._todos = todos;
this.save();
}
private save() {
localStorage.setItem(this.lsKey, JSON.stringify(this._todos));
}
可能会有帮助:聪明。非常感谢。