In a service I have a GET request to an API. My goal is to subscribe to the observable and assign a value to each element's property of the array in the response.
This is my service:
export class Service {
private readonly _sentinels = new BehaviorSubject<Sentinel[]>([]);
readonly sentinels$ = this._sentinels.asObservable();
public get sentinels(): Sentinel[] {
return this._sentinels.getValue();
}
public set sentinels(val: Sentinel[]) {
this._sentinels.next(val);
}
getSentinels(previousUrl?: string): Observable<Sentinel[]> {
const obsSentinels$ = this.http.get<Sentinel[]>(`${baseUrl}/sentinels`);
obsSentinels$.subscribe((sentinels) => {
if (previousUrl && sentinels && sentinels.length > 0) {
this.sentinels = this.setCameraStatusToTrue(sentinels);
} else {
this.sentinels = sentinels;
}
});
return obsSentinels$;
}
setCameraStatusToTrue(sentinels: Sentinel[]) {
sentinels.forEach((sentinel) => {
sentinel.cameraStatus = true;
});
// here the cameraStatus is equal to true
console.log('property');
console.log(sentinels[0].cameraStatus);
// here the cameraStatus in the object of the array is equal to undefined
console.log('object into array');
console.log(sentinels[0]);
return sentinels;
}
}
I don't really understand why in the result of setCameraStatusToTrue()
the property cameraStatus
of each object is undefined
.
Here is a pic of the console.log()