Encountered the following error message:
An issue arises with the type assignment in my TypeScript file which states - 'Type '{ id: number; name: string; price: number; quantity: number; status: string; description: string; imgaddress: string; } | undefined' is not assignable to type 'ProductInterface[]'. Type 'undefined' is not assignable to type 'ProductInterface[]'.ts(2322)'
while trying to retrieve the product ID from the main link (snapshot). Here's a snippet of my TypeScript file-
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { productsjson } from 'src/data/products';
import { ProductInterface } from 'src/product';
@Component({
selector: 'app-product-shop',
templateUrl: './product-shop.component.html',
styleUrls: ['./product-shop.component.css']
})
export class ProductShopComponent implements OnInit {
product!: ProductInterface;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
const routeParams = this.route.snapshot.paramMap;
const id = Number(routeParams.get("productId"));//error referenced here as **
this.product = productsjson.find(product => product.id === id);//another error occurs here
}
}
This is the structure of my product.ts interface file-
export interface ProductInterface{
id: number,
name: string,
price: number,
quantity: number,
status: string,
description: string,
imgaddress: string
}
Here is a glimpse into the contents of productsjson.ts file-
export const productsjson=[
{
id: 1,
name: 'Selenium',
price: 799,
quantity:2,
status:'In Stock',
description:'this course is for automation testing',
imgaddress:'https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg'
},
{
id: 2,
name: 'Java',
price: 1299,
quantity:5,
status:'In Stock',
description:'this course is for Java Programming Language',
imgaddress:'https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg'
}];