属性在Angular中抛出一个未定义的错误

时间:2018-05-31 04:01:26

标签: angular

出于某种原因,我在Angular 6应用程序中的各种对象上一直出现以下错误:

TypeError:无法读取未定义的属性“className”

这是我的一个组成部分:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { InspectionService } from '@shared/services/inspection.service';
import { Inspection } from '@shared/models/inspection';

@Component({
  selector: 'app-inspection-detail',
  templateUrl: './inspection-detail.component.html',
  styleUrls: ['./inspection-detail.component.scss']
})
export class InspectionDetailComponent implements OnInit {

  inspection: Inspection = new Inspection();
  hiveStrength: any;
  feedPriority: any;
  varroaCount: any;

  constructor(private route: ActivatedRoute,
    private inspectionService: InspectionService,
    private router: Router) {
  }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.inspectionService.getInspection(params['id']).subscribe((response) => {
        this.inspection = response.data;
        this.hiveStrength = this.inspectionService.getHiveStrengthById(this.inspection.hive_strength);
        this.feedPriority = this.inspectionService.getFeedPriorityById(this.inspection.feed_priority);
        this.varroaCount = this.inspectionService.getVarroaCountById(this.inspection.varroa_count);
        console.log(this.hiveStrength);
      });
    });
  }
}

相关模板部分

<div class="row">
  <div class="col-sm-4">
    <small-stat [statClass]="hiveStrength.className" [iconClass]="'fas fa-heart'" [label]="'Hive Strength'" [value]="hiveStrength.name"></small-stat>
  </div>
  <div class="col-sm-4">
    <small-stat [statClass]="feedPriority.className" [iconClass]="'fas fa-tint'" [label]="'Feed Priority'" [value]="feedPriority.name"></small-stat>
  </div>
  <div class="col-sm-4">
    <small-stat [statClass]="varroaCount.className" [iconClass]="'fas fa-bug'" [label]="'Varroa Count'" [value]="varroaCount.name"></small-stat>
  </div>
</div>

控制台日志正在返回有问题的对象,它在html模板中显示正常,但错误仍然存​​在。

有什么想法吗?我在另一个组件上有一个类似的问题在另一个组件上,所以我想知道我在这里做错了什么......

1 个答案:

答案 0 :(得分:1)

我认为您应首先检查在使用安全导航操作员在浏览器中打印数据时是否定义了数据。

  

Angular安全导航操作员(?。)流畅方便   防止属性路径中的null和未定义值的方法。

 <div class="col-sm-4">
    <small-stat [statClass]="hiveStrength?.className" [iconClass]="'fas fa-heart'" [label]="'Hive Strength'" [value]="hiveStrength?.name"></small-stat>
  </div>