Как отфильтровать базу данных firebase на основе значения флажка в анулярном - PullRequest
0 голосов
/ 20 июня 2020

У меня есть страница событий, где отображаются все события, и у всех событий есть поле категории. Моя база данных выглядит примерно так:

category:
  -categoryName

events:
  - evenName
  - category.id (I have stored id of category)

Прежде всего, я хочу отображать все события, и когда пользователь нажимает на флажки, я хочу отображать события на основе значения отмеченного флажка, также если пользователь снимает его выбор затем снова отобразите все события. помогите пожалуйста Я новичок в angular

Спасибо :)

events.service.ts

categories = null;
subscription;

/** Get Categories */
  getEventCategories() {
    if (!this.categories) {
      this.subscription = this.db
        .collection('categories')
        .valueChanges({ idField: 'id' })
        .subscribe(categories => (this.categories = categories));
    }
  }

/** Get Category Vise Events */
  getCategoryViseEvents(category: string) {
    return this.db
      .collection('events', ref => ref.where('eventCategory', '==', category))
      .valueChanges({ idField: 'id' });
  }

event.component.ts

import { Component, OnInit } from '@angular/core';
import { EventsService } from 'src/app/services/events.service';

@Component({
  selector: 'app-events-list',
  templateUrl: './events-list.component.html',
  styleUrls: ['./events-list.component.css']
})
export class EventsListComponent implements OnInit {
  events: any;
  mobile = false;
  loading = true;

  constructor(public eventService: EventsService) {}

  ngOnInit(): void {
    if (window.screen.width === 375) {
      // 768px portrait
      this.mobile = true;
    }

    this.eventService.getEventCategories();
    this.eventService.getAllEvents().subscribe(ev => {
      this.loading = false;
      this.events = ev;
    })
  }

  getCategory($event) {
    this.loading = true;
    if ($event.target.checked) {
      this.eventService.getCategoryViseEvents($event.target.id).subscribe(events => {
        this.events = events;
        this.loading = false;
      })
    } else {
      this.loading = false;
    }
  }
}

** event.component. html

<input
  type="checkbox"
  class="custom-control-input"
  [id]="category.id"
  (change)="getCategory($event)"/>

1 Ответ

1 голос
/ 21 июня 2020

Создайте вызов объекта allEvents в вашем сервисе. Я не вижу вашу функцию getAllEvents, но она должна загрузить свой результат в allEvents перед его возвратом. (Для этого вы можете подписаться на наблюдаемое 2 раза, один раз в сервисе и один раз в компоненте)

events.service.ts

categories = null;
subscription;
allEvents: Array<any> = [] // In here you will store your events in getAllEvents

/** Get Categories */
  getEventCategories(sendCategoriesCallback: function) {
    if (!this.categories) {
      this.subscription = this.db
        .collection('categories')
        .valueChanges({ idField: 'id' })
        .subscribe(categories => {
            this.categories = categories
            sendCategoriesCallback(this.categories)
        });
    }
  }

/** Get Category Vise Events */
  getCategoryViseEvents(category: string) {
    return this.allEvents.filter(event => event.category == category)
  }

event.component.ts

Как вы можете видеть здесь, я почти стер всех вас getCategoryVise .. , потому что фильтр не возвращает Наблюдаемый больше (это мгновенно).

import { Component, OnInit } from '@angular/core';
import { EventsService } from 'src/app/services/events.service';

@Component({
  selector: 'app-events-list',
  templateUrl: './events-list.component.html',
  styleUrls: ['./events-list.component.css']
})
export class EventsListComponent implements OnInit {
  events: any;
  mobile = false;
  loading = true;

  constructor(public eventService: EventsService) {}

  ngOnInit(): void {
    if (window.screen.width === 375) {
      // 768px portrait
      this.mobile = true;
    }

    this.eventService.getEventCategories((categories) => {
        this.categories = categories
    });

    this.eventService.getAllEvents().subscribe(ev => {
      this.loading = false;
      this.events = ev;
    })
  }

  getCategory($event) {
    this.loading = true;
    if ($event.target.checked) {
    this.events = this.eventService.getCategoryViseEvents($event.target.id)
  }
}

** event.component. html

Я добавил * ngFor инструкцию здесь

<input
  *ngFor="let category of categories"
  type="checkbox"
  class="custom-control-input"
  [id]="category.id"
  (change)="getCategory($event)"/>
...