簡體   English   中英

從 Angular Firestore 過濾 Observable

[英]Filtering an Observable from Angular Firestore

我已經看到了一些將過濾器應用於數據庫調用的答案。 我只需要調用數據庫一次,但無法弄清楚如何過濾 Firebase 返回的可觀察對象內的數組。

我有 2 個帶有標簽列表的選擇框。 我想從 Firestore 獲取整套項目並將其存儲在項目 Observable 中。 然后,當其中一個選擇框發生變化時,我想過濾該 observable,以便只顯示帶有這些標簽的項目。

items: Observable<any[]>;
  selectedTag1;
  selectedTag2;

  filteredItems: Observable<any[]>;

  tagName1 = ['', 'TAG1', 'TAG2', 'TAG3', 'TAG4'];
  tagName2 = ['', 'TAG5', 'TAG6', 'TAG7',

  constructor(db: AngularFirestore) {
  this.items = db.collection('items').valueChanges();
  }

  ngOnInit() {
    this.filteredItems = this.items.pipe(
      map((arr => arr.filter(item =>
        item.tags.some(s => s === this.selectedTag1) &&
        item.tags.some(s => s === this.selectedTag2))
        )));
  }

我的模板上根本沒有顯示任何項目。 當我使用選擇框更改 selectedTag 時。 我也沒有過濾項目。 有人可以建議我如何正確地做到這一點。 我需要 selectBoxes 來過濾是否只有一個值或兩者都有值。

HTML

<select [(ngModel)]="selectedTag1">
  <option  *ngFor="let item of tagName1">{{ item }}</option>
</select>

<select [(ngModel)]="selectedTag2">
  <option  *ngFor="let item of tagName2">{{ item }}</option>
</select>

<ul>
  <li class="text" *ngFor="let item of filteredItems | async">
    {{item.name}}
    <ul>
      <li *ngFor="let tags of item.tags">
        {{tags}}
      </li>
    </ul>
  </li>
</ul>

項目

[
  {
    "name": "Item 1",
    "tags": [
      "TAG1",
      "TAG4",
      "TAG5",
      "TAG6"
    ]
  },
  {
    "name": "Item 2",
    "tags": [
      "TAG2",
      "TAG3",
      "TAG5",
      "TAG7",
    ]
  }
]

我試圖添加一個在選擇框更改時運行的函數。

selectChanges() {
    this.filteredItems = this.items.pipe(
      map((arr => {
        console.log(arr);
        console.log(this.selectedTag1);
        arr.filter(item => {
        console.log(item.tags);
        item.tags.some(s => s === this.selectedTag1);} );
      })));
  }

但是我仍然沒有得到任何過濾結果。

正如您已經猜到的,您不應在所選標簽未定義或為空時進行過濾。 只需調整您的過濾邏輯,如下所示:

  filter() {
    this.filteredItems = this.items.pipe(
      map(arr =>
        arr.filter(item => {
          // return true if selectedTag1 or selectedTag2 is empty

          const matchesForTagName1 = this.selectedTag1
            ? item.tags.indexOf(this.selectedTag1) >= 0
            : true;
          const matchesForTagName2 = this.selectedTag2
            ? item.tags.indexOf(this.selectedTag2) >= 0
            : true;
          return matchesForTagName1 && matchesForTagName2;
        })
      )
    );
  }

您可以在此處查看 Stackblitz 中的完整示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM