我创建了一个已经困扰了一段时间的问题的基本示例。我有两个相同数组的服务:
properties1: Property[] = [];
properties2: Property[] = [];
和两种为这些数组分配值的方法:
getProperties1(): Property[] {
for (var i = 0; i < 5; i++) {
this.properties1[i] = new Property({
key: "" + i,
label: i + "",
value: i + "",
required: true,
order: i + 1
});
}
console.log("1.1: ", this.properties1);
console.log("1.2 : ", this.properties1[0]);
return this.properties1;
}
和:
getProperties2(): Property[] {
this.sampleService.justASample()
.subscribe(data => {
for (var i = 0; i < 5; i++) {
this.properties2[i] = new Property({
key: "" + i,
label: i + "",
value: i + "",
required: true,
order: i + 1
});
}
});
console.log("2.1: ", this.properties2);
console.log("2.2: ", this.properties2[0]);
return this.properties2;
}
如您所见,这些方法之间的唯一区别是,在第二种方法中,赋值发生在subscribe块内部(未故意使用订阅,因此更容易看到问题)。我在构造函数中调用了这两个方法:
constructor() {
this.getPoperties1();
this.getProperties2();
}
在console中,我可以看到第二个输出是不同的,基本上数组失去了它的属性,并且由于某种原因变得不确定。有谁知道如何修复它或为什么会发生?