代码之家  ›  专栏  ›  技术社区  ›  mightycode Newton

如何从对象数组在模板中显示属性

  •  0
  • mightycode Newton  · 技术社区  · 4 年前

    我只是尝试在模板中显示属性的值。但目前什么都没有显示。

    这就是组件:

    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) => {      
          });
      }
    }
    
    

    <p>Camera sensoren</p>
      <tr *ngFor="let camera of snovieStatusCollection.key|keyvalue">
    
        test
         <h3> {{camera | json}}</h3>
    
      </tr>
    

    所以我只想在模板中显示key的值。以及控制台.log返回以下内容:

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

    1 回复  |  直到 4 年前
        1
  •  2
  •   Michael D    4 年前

    两件事:

    1. 你不能从商店退任何东西 map . 所以呢 undefined 将发送到订阅。使用 tap 而不是副作用。
    2. this.sensorStatusCollection 在订阅中。
    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
          });
      }
    }
    

    更新:类型

    1. 正如@totalynewb在注释中指出的那样 需要是类型的数组 SensorStatusDto
    export class ServerStatusComponent implements OnInit {
      sensorStatusCollection: SensorStatusDto[] = [];
    
      ...
    }
    
    推荐文章