0

Product service:

   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:

  product:IProduct = null;

  id:any;

 

it doesn't matter what i'm trying, product is null!

when i'm doing console.log in the subscribe i can see the data! but the product still null. | -> I tried that also onInit same result -<

1 Answers1

0
  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'
 }

Line 'x' and 'z' execute first and at a later point of time when you get the response from the request the function passed to subscribe will be executed. So if you try to log the product outside this function you won't see data because this.product isn't assigned to it yet.

So you can check if this.product is assigned correctly inside the subscribe block.

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

And sending HTTP requests in the constructor is not a good practice. Do this in the ngOnInit lifecycle hook.

Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32