You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5如何从Firestore文档读取并列出嵌套用户邮箱数据

如何在Angular中获取Firestore文档内嵌套用户的邮箱?

嗨,我来帮你搞定这个问题~你现在拿不到邮箱的原因很简单:email字段并不是直接在company文档的根节点下,而是嵌套在users对象的某个用户ID(比如你示例里的123456789)下面,所以直接写{{cmp.email}}肯定找不到对应的属性。

下面分两种常见场景给你解决方案:

场景1:每个公司只有一个用户(或你明确知道要取的用户ID)

如果你的业务里每个company文档只会关联一个用户,或者你已经知道目标用户的ID,直接通过嵌套路径访问就行:

<li *ngFor="let cmp of comp | async">{{cmp.users['123456789'].email}}</li>

要是用户ID是动态的(比如当前登录用户的ID),可以先在组件里存好这个ID,再在模板里用变量,同时加个空值保护避免报错:
组件代码:

// 实际项目里可以从AngularFireAuth服务获取当前用户ID
currentUserId = '123456789';

模板代码:

<li *ngFor="let cmp of comp | async">{{cmp.users[currentUserId]?.email}}</li>

这里的?.是可选链操作符,防止users里没有对应ID时出现控制台报错。

场景2:每个公司有多个用户,需要列出所有邮箱

因为Firestore返回的users是对象(键为用户ID),而Angular的*ngFor只能遍历数组,所以我们得先把这个对象转换成数组才行,有两种方式:

方式一:在组件里预处理数据流

通过RxJS的map操作符,在组件里把每个company的users对象转成用户数组:

import { map } from 'rxjs/operators';

// ... 其他代码
this.compColl = this.afs.collection('companies');
this.comp = this.compColl.valueChanges().pipe(
  map(companies => companies.map(company => {
    // 把users对象转成包含用户ID和邮箱的数组
    company.userList = Object.entries(company.users).map(([userId, userData]) => ({
      userId,
      email: userData.email
    }));
    return company;
  }))
);

然后在模板里先遍历公司,再遍历每个公司的用户列表:

<ul *ngFor="let cmp of comp | async">
  <li *ngFor="let user of cmp.userList">{{user.email}}</li>
</ul>

方式二:用自定义管道在模板里转换

如果不想在组件里处理数据,可以写一个自定义管道,专门把对象转换成数组:
先创建管道文件(比如object-to-array.pipe.ts):

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'objectToArray' })
export class ObjectToArrayPipe implements PipeTransform {
  transform(obj: Record<string, any>): any[] {
    // 空值判断,避免传入undefined/null时报错
    return obj ? Object.entries(obj).map(([key, value]) => ({ key, ...value })) : [];
  }
}

记得在你的Angular模块里声明这个管道:

import { ObjectToArrayPipe } from './object-to-array.pipe';

@NgModule({
  declarations: [
    // ... 其他组件/管道
    ObjectToArrayPipe
  ]
})
export class YourModule { }

然后在模板里直接使用这个管道:

<ul *ngFor="let cmp of comp | async">
  <li *ngFor="let user of cmp.users | objectToArray">{{user.email}}</li>
</ul>

同样,要是users可能为空,记得加空值保护:cmp.users? | objectToArray。

内容的提问来源于stack exchange,提问作者quince

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:02