1
@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;
}

I want to instantiate product.title, product.category, and so on , but since product2 is instantiated by a async request i am not able to do so, how can i fix this issue. if(this.product2) block's code is never executed due to the async request.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Apr 28 '20 at 16:17
  • Yeah, Somewhat i already knew it was due to asynchronous behavior but wanted a way to make that work. Thanks! –  Apr 28 '20 at 17:47

1 Answers1

1

Move the code inside of the subscribe.

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;
      });


AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Also, this code has memory leaks. You should actually do that work inside the ngOnInit and unsubscribe inside the ngOnDestroy. – oiawo Apr 30 '20 at 21:00
  • The `take(1)` takes 1 emission and unsubscribes so it does not have memory leak. – AliF50 May 01 '20 at 01:15