要实现Angular和Firestore拖放任务列表的后端更新,可以按照以下步骤进行操作:
npm install firebase @angular/fire --save
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TaskService {
private tasksCollection: AngularFirestoreCollection;
tasks: Observable;
constructor(private firestore: AngularFirestore) {
this.tasksCollection = this.firestore.collection('tasks');
this.tasks = this.tasksCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Task;
const id = a.payload.doc.id;
return { id, ...data };
});
})
);
}
// 获取任务列表
getTasks(): Observable {
return this.tasks;
}
// 更新任务列表
updateTasks(tasks: Task[]): Promise {
const batch = this.firestore.firestore.batch();
tasks.forEach(task => {
const taskRef = this.tasksCollection.doc(task.id).ref;
batch.update(taskRef, task);
});
return batch.commit();
}
}
interface Task {
id?: string;
title: string;
completed: boolean;
}
import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { TaskService, Task } from './task.service';
@Component({
selector: 'app-task-list',
template: `
-
{{ task.title }}
`,
styles: [`
ul {
list-style-type: none;
}
`]
})
export class TaskListComponent {
tasks: Task[];
constructor(private taskService: TaskService) {
this.taskService.getTasks().subscribe(tasks => {
this.tasks = tasks;
});
}
drop(event: CdkDragDrop) {
moveItemInArray(this.tasks, event.previousIndex, event.currentIndex);
this.taskService.updateTasks(this.tasks);
}
}
在上面的示例中,我们使用Angular的拖放模块(@angular/cdk/drag-drop
)来实现任务列表的拖放功能。在用户拖动任务时,我们调用moveItemInArray
方法来更新任务数组中的任务顺序。然后,我们使用TaskService的updateTasks
方法将更改保存到Firestore中。
请注意,我们在TaskService中使用了batch.commit()
来将所有更新一次性提交到Firestore。这样可以减少与Firestore的通信次数,提高性能。
希望以上解决方法对你有帮助!