Skip to content
Advertisement

How to show in template property from array of objects

I just try to show the value of a property in the template. But at the moment nothing is shown.

So this is the component:

export class ServerStatusComponent implements OnInit {
  snovieCollection: SnovietatusDto = {};

  constructor(private snovierStatus: snovieStatusService) {}

  ngOnInit(): void {
    this.sensorStatus
      .getSensorStatuses()
      .pipe(
        map((data) => {
        console.log(data.cameraSensors);
        })
      )
      .subscribe((status) => {      
      });
  }
}

And this is the template:

<p>Camera sensoren</p>
  <tr *ngFor="let camera of snovieStatusCollection.key|keyvalue">

    test
     <h3> {{camera | json}}</h3>

  </tr>

So I just want to show in the template the value of key. And the console.log returns this:

0: {key: "T", latestTimestamp: "2021-03-12T10:09:00Z"}

So I don’t get any errors. But also nothing is shown.

Advertisement

Answer

Two things:

  1. You aren’t returning anything from the map. So undefined would be emitted to the subscription. Use tap for side-effects instead.
  2. You aren’t assigning the response to this.sensorStatusCollection in the subscription.
export class ServerStatusComponent implements OnInit {
  sensorStatusCollection: SensorStatusDto = {};

  constructor(private sensorStatus: SensorStatusService) {}

  ngOnInit(): void {
    this.sensorStatus
      .getSensorStatuses()
      .pipe(
        tap((data) => {                         // <-- `tap` here
          console.log(data.cameraSensors);
        })
      )
      .subscribe((status) => {      
        this.sensorStatusCollection = status;   // <-- assign here
      });
  }
}

Update: Type

  1. As pointed out by @TotallyNewb in the comments, the type of this.sensorStatusCollection needs to be an array of type SensorStatusDto
export class ServerStatusComponent implements OnInit {
  sensorStatusCollection: SensorStatusDto[] = [];

  ...
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement