假设我有一个以下结构,这意味着用户拥有包含对组的引用的对象数组。我需要为一组引用的组获得单个observable。我怎么做?我尝试了很多不同的方法,但没有一个是正确的。
这是我到目前为止所提出的:
export interface Group {
students: DocumentReference[];
title: string;
}
@Injectable()
export class GroupsService {
constructor(private afs: AngularFirestore, private tutorsService: TutorsService) { }
getCurrentTutorGroups(): Observable<Group[]> {
return this.tutorsService.tutor.pipe(
map(tutor => {
return tutor.groupSubjects.map(groupSubject => groupSubject.group.get());
}),
mergeMap(group => fromPromise(group)),
map(group => group.data() as Group)
);
}
}
GroupSubjects {
group: DocumentReference;
subject: DocumentReference;
}
interface Tutor extends User {
groupSubjects: GroupSubjects[];
}
@Injectable()
export class TutorsService {
tutor: Observable<Tutor>;
constructor(private afs: AngularFirestore, private authService: AuthService) {
this.tutor = this.authService.user.map((user: User) => {
return {...user} as Tutor;
});
}
}
export interface User {
uid: string;
email: string;
name: string;
role: string;
}
@Injectable()
export class AuthService {
user: Observable<User | null>;
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore) {
this.setUser();
}
private setUser() {
this.user = this.afAuth.authState
.switchMap((user) => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).snapshotChanges().map(action => {
return {uid: action.payload.id, ...action.payload.data()};
});
} else {
return Observable.of(null);
}
});
}
}
我需要函数getCurrentTutorGroups来返回类型为Group []的observable。
答案 0 :(得分:0)
这是我在所有斗争之后的解决方案
import { Injectable } from '@angular/core';
import {AngularFirestore} from 'angularfire2/firestore';
import {Observable} from 'rxjs/rx';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';
import { firestore} from 'firebase';
import DocumentReference = firestore.DocumentReference;
import {GroupSubjects, TutorsService} from './tutors.service';
import {fromPromise} from 'rxjs/observable/fromPromise';
export interface Group {
students: DocumentReference[];
title: string;
}
@Injectable()
export class GroupsService {
constructor(private afs: AngularFirestore, private tutorsService: TutorsService) { }
private getTutorGroupsObservableArray(groupSubjects: GroupSubjects[]): Observable<Group>[] {
return groupSubjects.map(groupSubject => fromPromise<Group>(groupSubject.group.get().then(group => group.data() as Group)));
}
getCurrentTutorGroups(): Observable<Group[]> {
return this.tutorsService.tutor.map(tutor => Observable.combineLatest(this.getTutorGroupsObservableArray(tutor.groupSubjects))).mergeMap(group => group);
}
}
&#13;
请记得添加
import {Observable} from 'rxjs/rx';
&#13;
而不是
import {Observable} from 'rxjs/Observable';
&#13;
另一件帮我找到方法的事情就是我为这段代码添加了我的私有方法更明显。