@Component({ selector: 'app-product-form', templateUrl: './product-form.component.html', styleUrls: ['./product-form.component.css']})export class ProductFormComponent implements OnInit { categories$; product:Product = {category:"", price:0, imageUrl:"",title:""}; product2; id; constructor( private router:Router, categoryService:CategoryService, private productService:ProductService, private route:ActivatedRoute) { this.categories$ = categoryService.getCategories().snapshotChanges(); this.id = this.route.snapshot.paramMap.get('id'); if(this.id) { this.productService .getOneProduct(this.id) .snapshotChanges() .pipe( take(1) ) .subscribe( p => this.product2 = p.payload.val()); if(this.product2){ this.product.category = this.product2.category; this.product.price = this.product2.price; this.product.imageUrl = this.product2.imageUrl; this.product.title = this.product2.title; } }export interface Product{ price:number; title:string; category:string; imageUrl:string;}我想实例化 product.title、product.category 等,但由于 product2 是由异步请求实例化的,我无法这样做,我该如何解决这个问题。由于异步请求,if(this.product2) 块的代码永远不会执行。
1 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
将代码移动到订阅中。
this.productService
.getOneProduct(this.id)
.snapshotChanges()
.pipe( take(1) )
.subscribe( p => {
this.product2 = p.payload.val();
// no more if check needed I assume
this.product.category = this.product2.category;
this.product.price = this.product2.price;
this.product.imageUrl = this.product2.imageUrl;
this.product.title = this.product2.title;
});
添加回答
举报
0/150
提交
取消