Angular 角度2:数据未出现在模板中
我已经多次成功地实现了这一点,但我肯定错过了一些东西。我的ngOnInit()函数调用DataService并返回一个产品,如下所示Angular 角度2:数据未出现在模板中,angular,Angular,我已经多次成功地实现了这一点,但我肯定错过了一些东西。我的ngOnInit()函数调用DataService并返回一个产品,如下所示 @Component({ selector: 'app-product-card', templateUrl: './product-card.component.html', styleUrls: ['./product-card.component.css'] }) export class ProductCardComponent impleme
@Component({
selector: 'app-product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent implements OnInit {
product: Product;
constructor(private dataService: DataService, private route:
ActivatedRoute) { }
ngOnInit() {
this.getProduct();
}
getProduct() {
this.route.params.subscribe(params => {
let id = params["id"];
this.dataService.getProduct(id).subscribe((product: Product) => {
this.product = product;
console.log("ProductCardComponent.product = " +
JSON.stringify(this.product));
})
})
}
}
但产品不会显示在模板中:
<div class="container-fluid">
<div class="col-sm-12">
<div *ngIf="product">
<div class="col-sm-1"></div>
<div class="col-sm-5">
<p>{{product.name}}</p>
<p>{{product.price}}</p>
</div>
<div class="col-sm-5">
fadfasdfadfasdf
</div>
</div>
</div>
</div>
从控制台日志中,您似乎看到的是一个
数组
,而不是对象
。因此,您必须获取第一个元素并分配。试试这个
this.product = product[0];
此语句中记录到控制台的内容是什么?log(“ProductCardComponent.product=“+JSON.stringify(this.product));是否已到达console.log行?是否已到达console.log。该产品已登录到控制台。能否显示控制台日志?我已将控制台日志添加到原始问题中。
this.product = product[0];