Каждый раз, когда вы вызываете метод watchedRivers()
, он возвращает новый массив объектов RiverInfo, содержащий Sample River 1, Sample River 2 and Sample River 3
. Поэтому назначение объекта updatedRiver на watchedRivers()[index]
не приведет к изменению объекта RiverInfo внутри метода.
Если вы хотите сохранить информацию updatedRiver, вы можете сделать это любым из двух способов, как показано ниже:
- Вместо того, чтобы возвращать массив из метода, вы можете сохранить его в переменной уровня класса.
class SomeClass {
// Storing the values in a class level variable
// so that it is accessible in all methods of this class
private watchedRivers: RiverInfo[] = [
{
name: "Sample River 1",
address: "Optional Address 1",
currentFlow: 2.78,
desiredMin: 1.5,
desiredMax: 6
},
{
name: "Sample River 2",
currentFlow: 857,
desiredMin: 100,
desiredMax: 500
},
{
name: "Sample River 3",
address: "Optional Address 1",
currentFlow: 2800,
desiredMin: 400,
desiredMax: 3000
}
];
updateFlows(index: number, updatedRiver: RiverInfo) {
console.log(updatedRiver);
this.watchedRivers[index] = updatedRiver;
console.log(this.watchedRivers[index]);
this.watchedRiversChanged.next(this.watchedRivers.slice());
}
}
Теперь обновления сохраняются в переменной уровня класса.
Если вы не хотите изменять метод, вы можете сохранить массив в локальной переменной, а затем выполнить лог c.
updateFlows(index: number, updatedRiver: RiverInfo) {
console.log(updatedRiver);
let localData = this.watchedRivers();
localData[index] = updatedRiver;
console.log(localData[index]);
this.watchedRiversChanged.next(localData.slice());
}