问题描述
我有一个产品列表,单击某个产品后,将打开产品详细信息,其中包含该产品的详细信息。 URL路径是产品的ID,即在数据库中获取然后搜索该产品的ID。但是要查看该产品的数据,我必须单击按钮。如何自动执行然后听更改?
product-details.component.ts:
export class ProductDetalisComponent implements OnInit {
private ngUnsubscribe = new Subject();
product = [];
product_id;
constructor(private productService: ProductService,private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.pipe(takeuntil(this.ngUnsubscribe))
.subscribe(params =>
{
this.product_id = [params.get('productId')];
this.getProductById();
});
}
getProductById() {
this.productService.getProductById(this.product_id)
.subscribe(
res => {
this.product = res;
},err => console.log(err)
);
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
product-details.component.html:
<button type="button" (click)="getProductById();">Product</button>
<p>Name: <a> {{product.name}} </a></p>
<p>Price: <a> {{product.price}} </a></p>
<p>Id: <a> {{product._id}} </a></p>
解决方法
您的意思是这样的吗?:
export class ProductDetalisComponent implements OnInit {
constructor(private productService: ProductService,private route: ActivatedRoute) { }
product = [];
product_id;
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product_id = params.get('productId');
this.getProductById(); // <=====
});
}
getProductById() {
this.productService.getProductById(this.product_id).subscribe(
res => {
console.log(res);
this.product = res;
},err => console.log(err)
);
}
}