筛选器输入选择合并Firestore

时间:2019-06-03 17:47:31

标签: javascript angular google-cloud-firestore

我有这两个Firestore过滤器,每个过滤器都运作良好,但彼此独立。我的问题是,有什么办法可以将它们结合起来?

enter image description here

也就是说,例如,如果我通过Categoría选择了一个过滤器,那么我尊重我选择的Departmento中的过滤器。

service.ts

filterByDepartamentos(departamento) {
  const byDepartamentos = this.afs.collection('eventos', ref => ref
  .where('departamento', '==', departamento)
  ).valueChanges();
  return byDepartamentos;
}

filterByCategorias(categoria) {
  const byCategorias = this.afs.collection('eventos', ref => ref
  .where('categoria', '==', categoria)
  ).valueChanges();

  return byCategorias;
}

component.ts

filtrarCategoria(categoria) {
  this.selectedCategoria = categoria;
  this.eventos = this.fs.filterByCategorias(categoria);
}

filtrarDepartamento(departamento) {
  this.selectedDepartamento = departamento;
  this.eventos = this.fs.filterByDepartamentos(departamento);
}

component.html

<div class="row">

  <mat-form-field appearance="outline" class="col-6">
    <mat-label>Departamento</mat-label>
    <mat-select [(ngModel)]="selectedDepartamento" (ngModelChange)="filtrarDepartamento(selectedDepartamento)">
      <mat-option *ngFor="let departamento of departamentos | async" [value]="departamento.nombre"> {{ departamento.nombre }}
      </mat-option>
    </mat-select>
    </mat-form-field>

  <mat-form-field appearance="outline" class="col-6">
    <mat-label>Categoría</mat-label>
    <mat-select [(ngModel)]="selectedCategoria" (ngModelChange)="filtrarCategoria(selectedCategoria)">
      <mat-option *ngFor="let categoria of categorias | async" [value]="categoria.nombre"> {{ categoria.nombre }}
       </mat-option>
      </mat-select>
     </mat-form-field>

   </div>

1 个答案:

答案 0 :(得分:0)

您可以将多个相等查询与Firestore结合使用。

这里是一个例子。如果只有两个过滤器,则可以简化操作-创建两个函数,其中第一个函数使用一个.where调用Firestore,另一个使用两个.where调用Firestore,但是如果您在未来。

组件:

<mat-select [(ngModel)]="selectedCategoria" (ngModelChange)="filtrarBy('selectedDepartamento', selectedDepartamento)">
<mat-select [(ngModel)]="selectedCategoria" (ngModelChange)="filtrarBy('selectedCategoria', selectedCategoria)">

ngOnInit() {
  this.eventos = this.fs.eventos; // subscribe or use async pipe before ngModelChange fires
}

filtrarBy(key, type) {
  this.fs.filterBy(key, type);
}

服务:

private eventosSub = new Subject();
eventos = eventosSub.asObservable().pipe(
  scan((filters, filter) => {...filters, ...filter }, {}),
  switchMap(filters => {
    const byFilters = this.afs.collection('eventos', ref => {
      let queryRef: any = ref;
      for (let key in filters) {
        if (filters[key]) {
          queryRef = queryRef.where(Object.keys(filters[key])[0], '==', filters[key])
        }
      } 
      return queryRef;        
    }).valueChanges();

    return byFilters;
  })
)

filtrarBy(key, type) {
  this.eventos.next({[key]: type});
}

这未经测试,仅是一个想法。让我知道