【问题标题】:Angular 11 how to map data from firestoreAngular 11如何从firestore映射数据
【发布时间】:2021-06-07 14:30:21
【问题描述】:

我正在尝试从 Firestore 获取数据,以显示在编辑组件模板中。我收到一条错误消息,提示“‘Observable’类型缺少‘Agency’类型的以下属性:agencyId、benefitCardName、benefitCardPhotoUrl、logoUrl 和另外 3 个。” 我的组件:

    agency$: Agency;

this.agency$  = this.activatedRoute.paramMap.pipe(switchMap(params => this.afs.collection<Agency>('agencies').doc<Agency>(`${params.get('agencyId')}`)
      .valueChanges().pipe(map( (data: Agency) =>
    {
      this.name = data.name,
      this.phone = data.phone;
    }))));
  console.log(this.agency$);

我的界面

export interface Agency {
  agencyId: Promise<string>;
  benefitCardName: string;
  benefitCardPhotoUrl: Promise<string>;
  logoUrl: Promise<string>;
  name: string;
  phone: string;
  pocTimesheetRequired: boolean;
}

【问题讨论】:

    标签: angular typescript google-cloud-firestore


    【解决方案1】:

    最后,我做了很多改变

    agency$: Observable<Agency> = this.afs.collection<Agency | any>('agencies').doc(this.agencyId)
        .valueChanges().pipe(tap(console.log),
          map( (agency: Agency) => {
            // agency
              // .map(data => {
            const logoUrl = this.afStorage.storage.refFromURL('').child(`/thumbnails/${this.agencyId}_700x100.png`)
              .getDownloadURL();
            const benefitCardPhotoUrl = this.afStorage.storage.refFromURL('').child(`/${this.agencyId}_200x200.png`)
              .getDownloadURL();
            this.logoUrl = logoUrl;
            this.benefitCardPhotoUrl = benefitCardPhotoUrl;
            return agency;
    })
    );
    

    【讨论】:

      【解决方案2】:

      我会定义可观察类型,这应该可以完成工作:

      this.afs.collection<Agency[]>('agencies').doc<Agency>(this.agencyId).valueChanges();
      

      如果这不能解决您的问题,您可以发布您如何使用 observable 吗?

      【讨论】:

      • 我稍微改变了我的功能,我还添加了你建议@Norbert Bartko 的类型,但我仍然遇到同样的错误。在这一点上,我只是在做console.log 来查看我的对象的样子,然后再准备进行插值。如果我将我的机构更改为这种类型:agency$: Observable;,我会得到一个匿名主题,但它显然没有正确映射。我所看到的只是正确的机构 ID
      猜你喜欢
      • 2022-10-23
      • 2021-10-27
      • 2022-01-01
      • 2019-07-03
      • 2018-06-13
      • 2022-08-04
      • 2021-09-03
      • 1970-01-01
      • 2021-02-07
      相关资源
      最近更新 更多