1

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()

console.log() of result

Abri
  • 43
  • 7
  • The code seems fine. Is there any code before `console.log('object into array');` – navnath Oct 15 '21 at 10:45
  • there is no such variable `this.sentinels` in the service. Share all possible code – navnath Oct 15 '21 at 10:47
  • @navnath thanks for your answer. I edited the service as you made me notice adding ``sentinels`` property. Before ``console.log('object into array');`` there is no code – Abri Oct 17 '21 at 11:08
  • [match your code with me](https://stackblitz.com/edit/angular-ivy-aiafdc?file=src%2Fapp%2Fservice.ts) – navnath Oct 17 '21 at 12:13
  • The response of my GET request is the same as yout fake datasource. I do not understand what I'm doing wrong – Abri Oct 17 '21 at 12:29
  • If You generate same issue with your code on stackblitz, I could help you. – navnath Oct 17 '21 at 12:31

0 Answers0