猛跑小豬
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;}我想實(shí)例化 product.title、product.category 等,但由于 product2 是由異步請(qǐng)求實(shí)例化的,我無(wú)法這樣做,我該如何解決這個(gè)問題。由于異步請(qǐng)求,if(this.product2) 塊的代碼永遠(yuǎn)不會(huì)執(zhí)行。
1 回答

拉莫斯之舞
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
將代碼移動(dòng)到訂閱中。
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;
});
添加回答
舉報(bào)
0/150
提交
取消