根据angularfirestore集合中子集合的字段值进行搜索

时间:2019-05-16 11:23:42

标签: angular firebase google-cloud-firestore angularfire2

尝试使用angularfirestore根据Firebase数据库的名称字段在列表中进行搜索。它甚至在控制台中都不显示任何错误。从服务中的代码返回的结果是一个空数组。我过滤并映射了构造函数中的有效负载数据,以获取异步数据并访问数据库中的嵌套对象

firebase collection

list.html:

    <input type="search" 
          class="form-control"
          [(ngModel)]="searchValue"
          [ngModelOptions]="{standalone: true}"
          (keyup)="searchMasjid()"
          placeholder="Name...">
  <div *ngIf="masjids$ | async; let masjids; else loading">
    <div class="card mb-1" *ngFor="let masjid of masjids">
      <div class="card-body d-flex justify-content-between">
        <div>
          <h5 class="mb-1">{{masjid.masjidInfo.jagah}}-{{masjid.masjidInfo.name}}</h5>
          <small>{{masjid.masjidInfo.address}}</small>
        </div>

list.ts:

export class MasjidListComponent{
  public masjids$: Observable<IMasjid[]>;
  masjids : Array<any>;
  searchValue: string = "";
  filterMasjidName: Array<any>;

  constructor(public firebaseService: FirebaseService, 
              public af: AngularFirestore){
                this.masjids$ = this.af.collection('masjids').snapshotChanges().pipe(
                  map( actions => actions.map(masjid => {
                    let data = masjid.payload.doc.data() as IMasjid;
                    let id = masjid.payload.doc.id;
                    return { id, ...data };
                  }))
                )
              }

  searchMasjid(){
    let value = this.searchValue;
    this.firebaseService.searchMasjids(value).subscribe(
     result => {
        this.filterMasjidName = result;
        this.masjids = this.combineMasjids(result, this.filterMasjidName)
     } 
    )
  }

  combineMasjids(a, b){
    let result = [];
    a.filter(x => {
      return b.filter(x2 =>{
        if(x2.payload.doc.id == x.payload.doc.id){
          result.push(x2);
        }
      });
    });
    return result;
  }
}

service.ts:

searchMasjids(searchValue){
    return this.db.collection('masjids.masjidInfo', 
    ref=>ref.where('name', '>=', searchValue)
    .where('name', '<=', searchValue + '\uf8ff')).snapshotChanges()
  }
}

1 个答案:

答案 0 :(得分:0)

据我所知,您的searchMasjids方法已经占用了结果,因为它调用了snapshotChanges()。这意味着searchMasjids的调用者会返回QuerySnapshot,而实际上却是一个Query

您应该返回集合/查询:

searchMasjids(searchValue){
    return this.db.collection(
      'masjids.masjidInfo', 
      ref => ref.where('name', '>=', searchValue)
                .where('name', '<=', searchValue + '\uf8ff')
    )
  }
}