猛跑小豬
2022-07-21 10:46:19
@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) 塊的代碼永遠不會執(zhí)行。
1 回答

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超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
提交
取消