如何使用Combinelatest

时间:2019-01-01 15:21:15

标签: angular typescript firebase observable combinelatest

这段代码的目标是将多个可观察对象存储到一个数组中,并将它们组合为一个可观察对象。

我尝试过使用forkjoin以及在将可观察对象推入数组之前在其周围添加()包装。

// standard index call that returns an observable<Model[]>
index(params?: IndexParameters): Observable<Model[]> {
    return this.afStore.collection<Model>(
        this.path, ref => {
            let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;

            if (!params)
                return query;
            if (params.limit)
                query = query.limit(params.limit);
            if (params.orderBy)
                query = query.orderBy(params.orderBy, params.orderDirection || 'asc');
            _.forEach(params.where, (v: CollectionWhere) => {
                query = query.where(v.fieldPath, v.operation, v.value);
            });

            return query;
        }).snapshotChanges()
        .pipe(map(actions => {
                return actions.map(a => {
                    const data = a.payload.doc.data();
                    const id = a.payload.doc.id;
                    return {id, ...data};
                });
            }),
            catchError(e => {
                FirebaseService.handleError(e);
                return throwError(e);
            }));
}

// store multiple observable<Model[]> into an array and keep entries that is present on all observable response
indexIntersection(ids: string[], fieldPath: string = 'id', intersectionBy: string = 'id'): Observable<Model[]> {
    const observables: Observable<Model[]>[] = [];

    _.forEach(ids, (v: string) => {
        observables.push(
            this.index({
                where: [{
                    fieldPath: fieldPath,
                    operation: '==',
                    value: v
                }]
            }).pipe(take(1)));
    });

    return combineLatest(...observables).pipe(
        take(1),
        map((res: Model[][]) => {
            return _.intersectionBy(...res, intersectionBy);
        })
    );
}

combineLatest将导致以下错误:

TypeError:您提供了一个无效对象,该对象应用于流。您可以提供一个Observable,Promise,Array或Iterable

0 个答案:

没有答案