[英]Angular subobject Object is possibly 'undefined'
我有一個從 api 返回的對象,這個對象有一個子對象。 當我在我的組件 html 中顯示這個子對象的屬性時,他工作了。 但是當我嘗試構建我的項目時,我收到以下錯誤:
對象可能是“未定義的”。
我的 html 組件代碼:
<img [src]="person?.gallery?.images[0]?.url" />
我也嘗試了下面的代碼,但現在工作並且很復雜:
<ng-container *ngIf="person !== undefined && person.gallery !== undefined && person.gallery.images !== undefined && person.gallery.length > 0 && person.gallery.images[0] !== undefined">
<img [src]="person?.gallery?.images[0]?.url" />
</ng-container>
在 localhost 中工作,但是當我執行 ng build –prod 時,我收到這些錯誤。
Angular 中的開發和生產模式是不同的。 根據您在項目中使用的設置,生產模式可能會進行額外檢查。
在您的情況下,請嘗試使用:
<ng-container *ngIf="person?.gallery?.images[0]?.url as u">
<img [src]="u" />
</ng-container>
我還建議重新考慮您的策略。 foo?.bar?.baz?.goo
結構看起來可以使用一個batter 實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.