Advertisement
Guest User

Untitled

a guest
Nov 29th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @Injectable()
  2. export class StudentService {
  3.  
  4.   results$ = new Subject<any>();
  5.   studentsAdded$ = new BehaviorSubject<any>(null);
  6.   private resultArray: any[] = [];
  7.  
  8.   constructor(private afs: AngularFirestore) { }
  9.  
  10.   getRecordsBySearch(searchText: any) {
  11.     // console.log(`MD: StudentService -> getRecordsBySearch -> getRecordsBySearch`);
  12.     this.resultArray = [];
  13.     this.results$.next([]);
  14.     if (searchText) {
  15.       // console.log(`MD: StudentService -> getRecordsBySearch -> searchText`, searchText);
  16.       const studentsRef = this.afs.collection('students').ref;
  17.       const fnameQuery = studentsRef.where('fname', '==', searchText);
  18.       const lnameQuery = studentsRef.where('lname', '==', searchText);
  19.       const gradeQuery = studentsRef.where('grade', '==', searchText);
  20.       const queries = [fnameQuery, lnameQuery, gradeQuery];
  21.       this.processQueries(queries);
  22.     }
  23.   }
  24.  
  25.   getRecordsByEmail(email: string) {
  26.     this.resultArray = [];
  27.     this.results$.next([]);
  28.     const studentsRef = this.afs.collection('students').ref;
  29.     const fe = studentsRef.where('fatherEmail', '==', email);
  30.     const me = studentsRef.where('motherEmail', '==', email);
  31.     const queries = [fe, me];
  32.     this.processQueries(queries);
  33.   }
  34.  
  35.   public processQueries(queries: Array<any>) {
  36.     queries.forEach(query => {
  37.     query.onSnapshot(querySnapshot => {
  38.       querySnapshot.docs.forEach(queryDocumentSnapshot => {
  39.         const data = queryDocumentSnapshot.data();
  40.         this.resultArray.push(data);
  41.         this.results$.next(this.resultArray);
  42.         });
  43.         // Prevent duplicates in array.  Duplication occurs upon a saved edit (assuming there was an actual change).
  44.       const u = this.resultArray.filter((e, i) => this.resultArray.findIndex(a => a.id === e.id) === i);
  45.       this.results$.next(u);
  46.        });
  47.     });
  48.   }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement