产品服务:
product:IProduct;
products:IProduct[] = [];
id:number;
constructor(private productSevice:ProductService, private route: ActivatedRoute) {
}
ngOnInit(): void {
this.id= parseInt(this.route.snapshot.paramMap.get('id'));
console.log(this.productSevice.products)
this.productSevice.getById(this.id).subscribe(data => {
this.product = data;
console.log(data)
})
console.log(this.product)
}产品:
product:IProduct = null;
id:any;不管我在尝试什么,产品都是空的!
当我在订阅中执行console.log时,我可以看到数据!但产品仍然是无效的。->我也尝试过同样的结果-<
发布于 2020-07-05 14:03:45
constructor(private productSevice:ProductService, private route: ActivatedRoute) {
this.id = this.route.snapshot.paramMap.get('id'); // line 'x'
this.productSevice.getById(this.id).subscribe(data => {
this.product = data; // line 'y'
});
console.log(this.product) // line 'z'
}行'x‘和'z’先执行,然后在从请求获得响应时执行传递给订阅的函数。因此,如果您尝试在此函数之外记录产品,就不会看到data,因为this.product还没有分配给它。
因此,您可以检查在订阅块中是否正确分配了this.product。
constructor(private productSevice:ProductService, private route: ActivatedRoute) {
this.id = this.route.snapshot.paramMap.get('id');
this.productSevice.getById(this.id).subscribe(data => {
this.product = data;
console.log(this.product)
});
}在构造函数中发送HTTP请求不是一个好做法。在ngOnInit生命周期挂钩中这样做。
https://stackoverflow.com/questions/62741261
复制相似问题