我正在处理问题。当我的一个属性被定义时,我的属性之一被显示为“未定义”,并且我找不到它的解决方案:
我有带有数据的父组件:
@Component({
selector: "app-my-products",
templateUrl: "./my-products.component.html",
styleUrls: ["./my-products.component.css"]
})
export class MyProductsComponent implements OnInit {
watched: WatchedProduct[] = [];
products: Product[] = [];
watchedProducts: Product[] = [];
ratings: ProductAvarageRating[] = [];
//then, i get data. It works fine
在 Parent.Component.html 中,我用数据调用两个子组件:
<div>
<app-my-products-ratings
[watchedProducts]="watchedProducts"
[ratings]="ratings"
></app-my-products-ratings>
<app-my-products-watched
[watchedProducts]="watchedProducts"
></app-my-products-watched>
</div>
MyProductsWatched.component.ts
如下所示:
@Component({
selector: "app-my-products-watched",
templateUrl: "./my-products-watched.component.html",
styleUrls: ["./my-products-watched.component.css"]
})
export class MyProductsWatchedComponent implements OnInit {
products: Product[] = [];
watched: WatchedProduct[] = [];
selectedProduct = new Product();
@Input() watchedProducts: WatchedProduct[] = []; //data from Parent here
还有他的 html:
<mat-list-item *ngFor="let product of watchedProducts">
<button mat-button>{{ product.name }}</button>
</mat-list-item>
效果很好。但在 MyProductRatings.component.html 中,我收到一个错误,来自 ratings 的属性之一未定义。
MyProductRatings
的组件:
@Component({
selector: "app-my-products-ratings",
templateUrl: "./my-products-ratings.component.html",
styleUrls: ["./my-products-ratings.component.css"]
})
export class MyProductsRatingsComponent implements OnInit {
@Input() watchedProducts: WatchedProduct[] = [];
@Input() ratings: ProductAvarageRating[] = []; //data from parent here
HTML:
<div>
<mat-selection-list>
<mat-list-item
*ngFor="
let product of (watchedProducts | search: searchText);
let i = index
"
>
<button mat-button>{{ watchedProducts[i].name }}</button>
{{ ratings[i].avarageRating }}
</mat-list-item>
</mat-selection-list>
</div>
我想要做的,是根据 *ngFor
的 index
从 ratings
获取名为 avarageRating
的属性> 循环。
例如,现在我在 watchedProducts
中有 2 个项目。我在 MyProductRatings.component.html
中的 html 中遇到的错误是:
ERROR TypeError: Cannot read property 'avarageRating' of undefined
但我得到了正确的评级(一切都显示良好)。
我的问题是,我做错了什么,我在控制台中出现了错误?
最佳答案
您观看的产品会在 avarageRating 之前加载。要么更改加载数据的方式,以便 avarageRating 然后加载 WatchedProducts。或者简单地添加一个 *ngIf="ratings[i]"这样它更像
<span> *ngIf="ratings[i]">{{ ratings[i].avarageRating }} </span>
最好稍后执行,因为如果评分数不等于观看的产品数,它可以解决问题。您将保护自己免受索引越界的影响。
关于Angular2 ngFor,存在时属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54011922/