So I'm new to angular... This code here:
ngOnInit(): void {
this.getProduct();
}
getProduct(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.product = this.products.getProduct(id);
console.log(this.product);
}
So first time this thing opens I get "TypeError: Cannot read property 'src' of undefined" And that console.log shows "undefined", but when I click home in the app and then click the same thing it works properly... Logs the right 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 has a list of products that was previusly loadedd from a .json file
constructor( private http: HttpClient ) {
this.getJSON().subscribe(data => {
this.products = data.products;
});
}
That module is used to make a grid of products so to avoid loading the .json twice I just imported it and reused it.
So if anyone can explain why it doesn't work the first time after loading the page (using ng serve of course) and why it does work every time after that, I'd really love you.
Edit, here is the template and the entire component.ts as per request:
<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);
}
}