for循环中的console.log
正确打印project
,role
和user
属性已更新proposer
。但是,当我离开循环时,尝试在底部打印相同的东西时,我更改的属性不会更新,而我获得的所有属性都是空的project
。那么如何在循环中“保存”project
?
project: Project = {
course: '',
title: '',
description: '',
proposer: [{role: '', user: ''}],
approved: false,
responsible: [{role: '', user: ''}],
advisor: [{role: '', user: ''}],
examiner: [{role: '', user: ''}],
student: []
};
populateSchema() {
var proposerFound = false;
for (var key in this.project.proposer) {
this.employeeService.getEmployee(this.project.proposer[key].user)
.then((employee: Employee) => {
if (employee != null) {
proposerFound = true;
this.project.proposer[key].role = 'Employee';
this.project.proposer[key].user = employee._id;
console.log(this.project); // updated attributes
}
});
}
console.log(this.project); // NOT updated attributes, empty
答案 0 :(得分:1)
您正在承诺中执行更新。您的最后一个控制台行在当时......
之前执行这应该有效:
populateSchema() {
var proposerFound = false;
var promises: Promise<void>[] = [];
for (let key in this.project.proposer) {
promises.push(this.employeeService.getEmployee(this.project.proposer[key].user)
.then((employee: Employee) => {
if (employee != null) {
proposerFound = true;
this.project.proposer[key].role = 'Employee';
this.project.proposer[key].user = employee._id;
console.log(this.project); // updated attributes
}
}));
}
Promise.all(promises).then(() => {
console.log(this.project);
});
}