【问题标题】:How to query and display subcollections with Angular?如何使用 Angular 查询和显示子集合?
【发布时间】:2020-09-09 19:20:25
【问题描述】:

我正在开发我的第一个 angular/firestore 应用程序,并且已经到了可以显示单个集合中的文档数据而没有子集合的地步。我正在尝试对此进行扩展并显示子集合中的数据。我的 Firestore 数据库如下所示。

用户->用户ID->战斗->战斗ID

我现在正试图在我的页面上显示战斗,所以我试图查询 Fights 的子集合并将其编码到我的组件中。

我的 TS:

    @Component({
     selector: 'app-my-fights',
    templateUrl: './my-fights.component.html',
    styleUrls: ['./my-fights.component.css']
    })
    export class MyFightsComponent implements OnDestroy, OnInit {

    
    userId: any;
    fights$: Observable<any>;
    users$: Observable<any>;
    user: any;
    private readonly subscription: Subscription;
    fightCollection: AngularFirestoreCollection<any>;

   

    
     constructor(private afs: AngularFirestore, private firestoreData: FirestoreDataService, public auth: 
    AuthService, private fightTest: FightService) {
    this.subscription = auth.user$.subscribe(user => {
    this.userId = user.uid
    this.fightCollection = this.afs.collection<any>(`users/${this.userId}/Fights`);
    this.fights$ = this.fightCollection.valueChanges();
    
  
       });
      }

      ngOnInit() {
   
       }

      ngOnDestroy() {
       this.subscription.unsubscribe();
  
    
     }

    }

用户 ID 是从我创建的注入身份验证服务中提取的。我将 userID 放入一个变量中只是为了测试我是否可以正确提取 uid。然后我尝试将 userId 值编码到正确的 firestore 路径中,以提取用户 Fights 集合并将其分配给 observable。

我的 HTML:

      <ul *ngFor="let fight of fights | async">
     <li>
      fight.blueFighter;
     </li>
    </ul>

为了简单起见,我现在只是尝试拉出 blueFIghter 字段。

我没有收到任何错误,但也没有显示任何内容。我不知道我是否正确地阅读了该集合,或者只是没有正确地在 HTML 中调用它。

【问题讨论】:

标签: angular google-cloud-firestore angularfire2


【解决方案1】:

尝试改变构建 observables 的方式。不要在订阅中定义它们。改用更高的 observable。

    ...
    this.fights$ = auth.user$.pipe(
        tap(user => console.log('is user emitting?: ', user)),
        take(1),
        mergeMap(user => {
            this.userId = user.uid
            this.fightCollection = this.afs.collection<any>(`users/${this.userId}/Fights`);
            return this.fightCollection.valueChanges();
        }),
        tap(fights => console.log('fights value: ', fights))
    );
    ...

添加tap 运算符可以帮助您了解您的可观察对象是否真的在发射某些东西。

另外,我认为你的 html 中有一个错字,应该是打架$:

<ul *ngFor="let fight of fights$ | async">
 <li>
  {{fight.blueFighter}}
 </li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2018-10-08
    • 1970-01-01
    • 2019-07-20
    • 2021-10-26
    • 2019-03-27
    相关资源
    最近更新 更多