Just starting my Angular journey... Here's some code snippet:
ngOnInit(): void {
this.getProduct();
}
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.product = this.products.getProduct(id);
console.log(this.product);
}
When I first open this, I get "TypeError: Cannot read property 'src' of undefined" The console.log shows "undefined", but when I navigate home and then come back, it works perfectly... Logs the correct item and displays the right image
public getProduct(id: number): Product {
// console.log('returning product');
return (this.products.find(product => product.id === id));
}
The module that returns the list of products was previously loaded from a .json file
constructor( private http: HttpClient ) {
this.getJSON().subscribe(data => {
this.products = data.products;
});
}
This module is used to create a grid of products, so to avoid loading the .json file twice, I imported it and reused it.
If anyone can explain why it doesn't work the first time after loading the page (using ng serve) and why it works fine every subsequent time, I would greatly appreciate it.
Edit, here is the template and the entire component.ts as requested:
<div>
<img src="{{product.src}}" alt="">
</div>
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Product } from '../classes/product.interface';
import { ShoppingGridComponent } from '../shopping-grid/shopping-grid.component';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
product: Product;
constructor(
private route: ActivatedRoute,
private location: Location,
private products: ShoppingGridComponent
) {}
ngOnInit(): void {
this.getProduct();
}
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
console.log(id);
this.product = this.products.getProduct(id);
console.log(this.product);
}
}