Используйте фильтр поиска на AngularFireCollection в Ionic - PullRequest
0 голосов
/ 17 февраля 2020

У меня есть код службы данных в файле firestore.service.ts:

import { Injectable } from '@angular/core';
import { AngularFirestore, 
         AngularFirestoreCollection,
         AngularFirestoreDocument 
       } from '@angular/fire/firestore';

import { Song } from '../../models/song.interface';

import { Router } from '@angular/router'

@Injectable({
  providedIn: 'root'
})
export class FirestoreService {

  constructor(public firestore: AngularFirestore, public router: Router) {}

    createSong(
        albumName: string,
        artistName: string,
        songDescription: string,
        songName: string
    ): Promise<void> {

        const id = this.firestore.createId();

        return this.firestore.doc(`songList/${id}`).set({
            id,
            albumName,
            artistName,
            songDescription,
            songName,
        });
    }

  getSongList(): AngularFirestoreCollection<Song> {
  return this.firestore.collection(`songList`);
  }

  getSongDetail(songId: string): AngularFirestoreDocument<Song> {
  return this.firestore.collection('songList').doc(songId);
  }

}

Моя домашняя страница, которая отображает список, home.page.ts:

import { Component } from '@angular/core';

import { AngularFirestoreCollection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Song } from '../models/song.interface';
import { FirestoreService } from '../services/data/firestore.service';

import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

    public songList: AngularFirestoreCollection<Song>;
    public loadedSongList : AngularFirestoreCollection<Song>;

    constructor(
        private firestoreService: FirestoreService,
        private router: Router
        ) {}


    ngOnInit() {
        this.songList = this.firestoreService.getSongList().valueChanges();
        this.loadedSongList = this.songList;
    }

    initializeItems(): void {
        this.songList = this.loadedSongList;
    }


    filterList(evt) {
        this.initializeItems();

        const searchTerm = evt.srcElement.value;

        if (!searchTerm) {
            return;
        }

    this.songList = this.songList.filter(currentSong => {
        if (currentSong.songName && searchTerm) {
            if (currentSong.songName.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1) {
                return true;
            }
        return false;
            }
        });
    }

}

И мой список отображается на домашней странице. html примерно так:

<ion-header>
  <ion-toolbar>
    <ion-title>Song List</ion-title>
    <ion-buttons slot="end">
      <ion-button routerLink="/create">
        <ion-icon slot="icon-only" name="add"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-searchbar
    showcancelbutton=""
    (ioninput)="filterList($event)"
  ></ion-searchbar>
  <ion-card
    *ngFor="let song of songList | async"
    routerLink="/detail/{{song.id}}"
  >
    <ion-card-header>
      {{ song.songName }}
    </ion-card-header>
    <ion-card-content>
      Artist Name: {{ song.artistName }}
    </ion-card-content>
  </ion-card>
</ion-content>

enter image description here

Единственная проблема в том, что моя панель поиска вообще не работает , Там также нет никаких ошибок. Я попытался изменить его и подписаться на AngularFirestoreCollection перед тем, как вместо asyn c pipe, но у меня серьезные ошибки с проблемами типа Ovservable vs Array. Мне просто интересно, может ли кто-нибудь помочь мне понять, где я ошибаюсь, поэтому панель поиска работает для меня. Я могу отображать данные без проблем с моим текущим кодом.

Любая помощь будет принята с благодарностью.

...