[英]How to wait for data to be loaded from Firestore before running functions Angular
I have a service that reads the data from Cloud Firestore from employee.service.ts
:我有一项服务可以从
employee.service.ts
读取来自 Cloud Firestore 的数据:
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
:我使用此服务从
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
}
}
Every time the selectOrg
input gets set, it runs getEmployees
and formsInit
synchronously.每次设置
selectOrg
输入时,它都会同步运行getEmployees
和formsInit
。 The problem is that I need some of the data from getEmployees()
to be completely loaded before I run formsInit()
.问题是我需要在运行
formsInit()
之前完全加载来自getEmployees()
的一些数据。
How do I rewrite this code so that formsInit
waits for getEmployees
to complete its async operations?我如何重写这段代码,以便
formsInit
等待getEmployees
完成其异步操作?
Edit 1:编辑 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.我现在能想到的最好的办法是修改
getEmployees()
以接受一个可选参数,即 function 以便它在检索到数据后运行。 Not sure how practical or clean that would be, though.不过,不确定那会有多实用或干净。
You could just call formsInit()
from your getEmployees
function like so:您可以像这样从
getEmployees
function 调用formsInit()
:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.