Hello!
I have 2 Services. One for Subjects, one for Teachers. The Data is stored in the Firebase Firestore.
My Subject Object has a property named teacherId. Then i get the Subject objects from Firebase, I want to get the teacher based on its Id stored in subject from the teacherservice. But i do not know how to do this. I tried the following but i doesn’t work:
import { TeacherService } from './../teacher/teacher.service';
import { Subject } from './../../objects/subject';
import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection} from 'angularfire2/firestore'
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SubjectService {
private subjectsCollection : AngularFirestoreCollection<Subject>;
private subjects :Observable<Subject[]>;
public subjectsLocal;
constructor(db : AngularFirestore, private teacherService : TeacherService ) {
this.subjectsCollection = db.collection<Subject>('subjects');
this.subjects = this.subjectsCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const id = a.payload.doc.id;
let data = a.payload.doc.data();
this.teacherService.getTeacher("S7XHgaMhpywmezusLrp2").subscribe(res => {
data.name = res.name;
});
return {id, ...data};
});
}));
}
getSubjects() {
return this.subjects;
}
getSubject(id) {
return this.subjectsCollection.doc<Subject>(id).valueChanges();
}
updateSubject(subject : Subject, id : string) {
return this.subjectsCollection.doc(id).update(subject);
}
addSubject(subject : Subject) {
this.subjectsCollection.add(subject);
}
removeSubject(id) {
this.subjectsCollection.doc(id).delete();
}
}
The Teacherservice looks like this:
import { Teacher } from './../../objects/teacher';
import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection} from 'angularfire2/firestore'
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TeacherService {
private teachersCollection : AngularFirestoreCollection<Teacher>;
private teachers :Observable<Teacher[]>;
public teachersLocal;
constructor(db : AngularFirestore ) {
this.teachersCollection = db.collection<Teacher>('teachers');
this.teachers = this.teachersCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const id = a.payload.doc.id;
const data = a.payload.doc.data();
return {id, ...data};
});
}));
}
getTeachers() {
return this.teachers;
}
getTeacher(id) {
return this.teachersCollection.doc<Teacher>(id).valueChanges();
}
updateTeacher(teacher : Teacher, id : string) {
return this.teachersCollection.doc(id).update(teacher);
}
addTeacher(teacher : Teacher) {
this.teachersCollection.add(teacher);
}
removeTeacher(id) {
this.teachersCollection.doc(id).delete();
}
}
The value of res in subjectservice contains the correct data but it does not apply to the subject.
Is where a solution?
Thanks!