Angular查询Firestore集合文档 提取手机号存入数组的实现方法
Firestore提取手机号存入数组解决方案
核心修改后代码
// 组件内先声明存储手机号的全局数组属性,方便其他函数调用 public phoneNumberList: string[] = []; async getPhone() { const snapshot = await this.afs.collection('members', ref => ref.where('phoneNumber', '>=', 0)) .get() .toPromise(); if (snapshot.empty) { console.log('No Matches'); this.phoneNumberList = []; return; } // 直接调用处理逻辑拿到数组赋值给全局属性 this.phoneNumberList = this.extractPhoneNumbers(snapshot.docs); // 此处已拿到完整数组,可直接传给其他函数使用 console.log('最终手机号数组:', this.phoneNumberList); } extractPhoneNumbers(docs: firebase.firestore.QueryDocumentSnapshot[]) { const resultArray: string[] = []; docs.forEach(doc => { const docData = doc.data(); // 可选:加非空判断避免部分文档无此字段时存入空值 if(docData?.phoneNumber) { resultArray.push(docData.phoneNumber); } }); return resultArray; }
更简洁的简化写法
可以直接用数组map方法替代循环,无需单独写处理函数:
public phoneNumberList: string[] = []; async getPhone() { const snapshot = await this.afs.collection('members', ref => ref.where('phoneNumber', '>=', 0)) .get() .toPromise(); if (snapshot.empty) { console.log('No Matches'); this.phoneNumberList = []; return; } // 一行代码完成字段提取生成数组 this.phoneNumberList = snapshot.docs.map(doc => doc.data().phoneNumber).filter(Boolean); }
主要修改说明
- 原代码中数组定义在
forEach循环内部,每次遍历都会重置数组,导致最终只能拿到最后一个值,调整后将数组声明在遍历逻辑外部 forEach方法的返回值没有实际作用,调整为遍历完成后统一返回完整数组,或直接用map方法直接生成目标数组- 新增全局数组属性存储最终结果,组件内其他函数可以直接调用该属性获取所有手机号
- 可选添加非空过滤逻辑,避免部分文档缺失
phoneNumber字段时存入无效空值
内容的提问来源于stack exchange,提问作者Tony B
相关产品推荐
相关产品推荐

