通过合并和嵌套switchMap获取子集合

时间:2019-04-25 09:44:40

标签: firebase google-cloud-firestore ionic4

我的firebase数据结构:

// Listings:
{
    "id1": {
        "title": "Title of id1",
        "category": "cat1",
        "location": "loc1",
        // ...
    },
    "id2": {
        "title": "Title of id2",
        "category": "cat2",
        "location": "loc1",
        // ...
    }
}

// Categories:
{
    "cat1": {
        "name": {
            "de": "Kategorie 1",
            "en": "Category 1"
        },
        "total": 1
    },
    "cat2": {
        "name": {
            "de": "Kategorie 1",
            "en": "Category 1"
        },
        "total": 1
    }
}

// Locations:
{
    "loc1": {
        "name": {
            "de": "Ort 1",
            "en": "City 1"
        },
        "total": 2
    }
}

我在组件/模板(具有异步功能)中使用的我的listing.service.ts:

import {Injectable} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, pipe} from 'rxjs';
import {AngularFirestore, AngularFirestoreCollection} from '@angular/fire/firestore';
import {map, switchMap, take} from 'rxjs/operators';

import { ListingModel } from '../models/listing.model';

@Injectable()
export class ListingService {
    private listings: Observable<any>;
    private listingCollection: AngularFirestoreCollection<ListingModel>;
    catFilter: BehaviorSubject<string|null>;
    locFilter: BehaviorSubject<string|null>;

    constructor (private db: AngularFirestore) {
        this.listingCollection = this.db.collection<ListingModel>('listings');
        this.cityFilter = new BehaviorSubject(null);
        this.catFilter = new BehaviorSubject(null);
        this.listings = combineLatest(
            this.cityFilter,
            this.catFilter
        ).pipe(
            switchMap(([ort, kategorie]) => this.db.collection('listings', ref => {
                let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
                if (ort) {
                    query = query.where('loc', '==', ort);
                }
                if (kategorie) {
                    query = query.where('cat', '==', kategorie);
                }
                query.orderBy('date');
                return query;
            }).snapshotChanges().pipe(
                map( actions => actions.map( a => {
                    const data: any = a.payload.doc.data() as ListingModel;
                    const id: string = a.payload.doc.id;
                    return { id, ...data };
                }))
            );
        );
    }
    filterByCat(cat: string|null) {
        this.catFilter.next(cat);
    }
    filterByLocation(loc: string|null) {
        this.locFilter.next(loc);
    }
}

现在的问题是,我不了解如何在CombineLatest和switchMap中包括子集合类别和位置,因此每个列表的类别和位置都包含在可观察对象中。

有人可以在这里帮助我吗?

0 个答案:

没有答案