AngularFirestore - Update query dynamically

允我心安 提交于 2020-07-20 03:42:20

问题


I have the following query:

loadData(settings: any): Observable<any[]> {
    const ref = this.db.collection('data').ref
      .orderBy('simpleID', 'desc')
      .where('isVerified', '==', true)
      .limit(5);
    // Gender filter
     if (settings.includeMales && !settings.includeFemales) {
       ref.where('gender', '==', 'm');
     } else if (!settings.includeMales && settings.includeFemales) {
       ref.where('gender', '==', 'f');
     }

return this.db.collection('confessions', ref => ref)
      .valueChanges();

I want to apply filters dynamically based on the settings object.

How can I use the ref variable and pass it to the collect() method of Angularfire2?


回答1:


Every time you call a where() or other method, it actually returns a new query. So you just need to make sure to capture the query of each call.

var query = this.db.collection('data').ref
  .orderBy('simpleID', 'desc')
  .where('isVerified', '==', true)
  .limit(5);
if (settings.includeMales && !settings.includeFemales) {
  query = query.where('gender', '==', 'm');
} else if (!settings.includeMales && settings.includeFemales) {
  query = query.where('gender', '==', 'f');
}

return this.db.collection('confessions', ref => query).valueChanges();


来源:https://stackoverflow.com/questions/51221167/angularfirestore-update-query-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!