Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire

How to wait for data to be loaded from Firestore before running functions Angular


Current situation:

I have a service that reads the data from Cloud Firestore from employee.service.ts:

getEmployeeList(orgID: string) {
    return this.firestore.collection('orgData').doc(orgID).collection('employeeList').snapshotChanges();
  }

I use this service to read the data in my component from component.ts:

export class ManageEmployeesComponent implements OnInit {
    newEmployee: FormGroup;
    Employees: Employee[];

    selectedOrganization: string;
  
    @Input() set selectOrg(org: string) {
      this.selectedOrganization = org;
      this.getEmployees();
      this.formsInit();
    }

    getEmployees() {
      this.employeeService.getEmployeeList(this.selectedOrganization).subscribe(data => {
        this.Employees = data.map(e => {
          return {
            id: e.payload.doc.id,
            ...e.payload.doc.data() as Employee
          };
        })
      });
    }

    formsInit() {
        //some reactive form stuff
    }
}

The problem:

Every time the selectOrg input gets set, it runs getEmployees and formsInit synchronously. The problem is that I need some of the data from getEmployees() to be completely loaded before I run formsInit().

Question

How do I rewrite this code so that formsInit waits for getEmployees to complete its async operations?

Edit 1:
The best I can think right now is to modify getEmployees() to accept an optional argument that is a function for it to run once the data is retrieved. Not sure how practical or clean that would be, though.


Solution

  • You could just call formsInit() from your getEmployees function like so:

    export class ManageEmployeesComponent implements OnInit {
        newEmployee: FormGroup;
        Employees: Employee[];
    
        selectedOrganization: string;
      
        @Input() set selectOrg(org: string) {
          this.selectedOrganization = org;
          this.getEmployees();
        }
    
        getEmployees() {
          this.employeeService.getEmployeeList(this.selectedOrganization).subscribe(data => {
            this.Employees = data.map(e => {
              return {
                id: e.payload.doc.id,
                ...e.payload.doc.data() as Employee
              };
            });
            this.formsInit();
          });
        }
    
        formsInit() {
            //some reactive form stuff
        }
    }