[AngularFire2] Update multi collections at the same time with FirebaseRef
At some point, you might need to udpate multi collections and those collections should all updated successfully, otherwise we don't update anything. You can use 'FirebaseRef' to get the root node (the parent all for the collections).
constructor(private rt: RealtimeService, @Inject(FirebaseRef) fb) { this.rootDb = fb.database().ref(); // To get the root firebase ref }
You can inject 'FirebaseRef' by using @Inject.
For example we want to update 'lessons' and 'lessonsPreCourse' at the same time, make sure if both sucess, both get udpated, one has error then abort the transaction:
To add value into lessonsPerCourse key, we need to grap the new Lesson key first.
To do that, we can generate a new lesson key by doing:
const newLessonKey = this.rootDb.child('lessons').push().key;
This won't actually insert a row into the 'lessons' table, it just create a new key for lessons collection for us to use locally.
Once we got the new lesson key, then we can update the table by calling 'update()' on 'this.rootDb':
this.rootDb.update(dataToSave) .then( (val) => { }, (err) => { });
The full code for create new lesson:
createNewLesson(courseId: string, lesson: Lesson): Observable<any>{ const lessonToSave = Object.assign({}, lesson, {courseId}); // Generate a new key under 'lessons' collection, db won't change currently const newLessonKey = this.rootDb.child('lessons').push().key; const dataToSave = {}; dataToSave[`lessons/${newLessonKey}`] = lessonToSave; dataToSave[`lessonsPerCourse/${courseId}/${newLessonKey}`] = true; const subject = new Subject(); this.rootDb.update(dataToSave) .then( (val) => { subject.next(val); subject.complete(); }, (err) => { subject.error(err); subject.complete(); }); return subject.asObservable(); }
Notice that, we also use Subject(), because the function expect to return an Observable. So we call:
return subject.asObservable();
Also we call complete() method everytime, this is important to complete a subject.
subject.complete();
To mention that, subject is not the only way to can convert Promise to Observable, we can also do:
return Observable.fromPromise(this.rootDb.update(dataToSave));
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2014-11-10 [Firebase] 2. Firebase Event Handling
2014-11-10 [Firebase] 1. AngularFire, $save, $add and $remove, Forge