为什么我得到类型错误:即使组件正确呈现,也无法读取未定义的属性(读取"公司")



我正试图通过以下方式将一些公司数据从api中获取到该组件中:


@Component({
selector: 'app-company-details',
templateUrl: './company-details.component.html',
styleUrls: ['./company-details.component.css']
})
export class CompanyDetailsComponent implements OnInit, OnChanges, OnDestroy {
@Input() companyId!: number
company! : CompanyInterface
subscription! : Subscription
constructor(private companiesService : CompaniesService) { }
ngOnChanges(changes: SimpleChanges) {
}
ngOnInit(): void {
this.subscription = this.companiesService.getCompanyDetails(this.companyId)
.subscribe(response => {
this.company = response
})
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
}

我在这里所做的是从父组件中获取companyId作为输入,然后使用它通过CompaniesService获取数据,然后将数据显示到组件的HTML模板中,如下所示:

<article class="company-details">
<h4>COMPANY DETAILS</h4>
<div class="company-description">
<h5>DESCRIPTION</h5>
<p>{{company.description}}</p>
</div>
<div class="company-locations">
<h5>LOCATIONS</h5>
<p>We are in:
<span *ngFor="let location of company.locations">{{location.name}},</span>
</p>
</div>
<div class="company-size">
<span><h5>SIZE: {{company.size.short_name | uppercase}}</h5> </span>
</div>
<mat-divider></mat-divider>
</article>

一切正常,数据呈现正确,但在控制台中,我收到了以下错误:
ERROR TypeError: Cannot read properties of undefined (reading 'company')

我在这里做错了什么?这与组件的生命周期有关吗?

尝试使用?在TypeScript中。更新这行,它应该是好的。

<span *ngFor="let location of company?.locations">{{location.name}},</span>

此外,您还可以使用async管道来制作更干净的解决方案。

// In your component typescript file
company$ : CompanyInterface
ngOnInit(): void {
this.company$ = this.companiesService.getCompanyDetails(this.companyId);
}
// In HTML
<span *ngFor="let location of company$ | async">{{location?.name}},</span>

在这种情况下,您将避免订阅和取消订阅。

最新更新