I have some problems about using json with angular.
In my project I generate components.
And I delete spec.ts.
After that I create a file named prod.data.json
{
"products" :
[
{
"sku" : "10",
"name" : "Laptop Blue Background",
"saleTag" : false,
"prodImage" : "img",
"price" : "210",
"discountly" : "200",
"revives" : "3",
"summary" : "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only",
"availability" : "In Stock",
"categori" : "Business",
"tag" : "Book",
"share" : {
"facebook" : "link",
"twitter" : "link",
"instagram" : "link",
"linkedin" : "link"
},
The json codes format are like that.
And content.companents.ts named file codes are..
import prodData from '/Users/obasekin/angular-crash/src/app/prod.data.json';
interface Product {
sku: Number;
name: String;
saleTag: String;
prodImage: String;
price: Number;
discountly: Number;
revives: Number;
summary: String;
availability: String;
catagori: String;
tag: String;
share: {
facebook: String;
twitter: String;
instagram: String;
linkedin: String;
};
description: {
desSummary: String;
desList: {
lineMono: String;
lineDi: String;
lineTri: String;
lineTetra: String;
linePenta: String;
lineHexa: String;
};
};
}
I import the format which is String or Number.
My problem is in this code..
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
constructor() { }
products: Product[] = prodData;
ngOnInit(): void {
}
}
products is have problem in this line
products: Product[] = prodData;
issues ss here..
Update 1
I have tsconfig.json
"resolveJsonModule": true,
"esModuleInterop": true
Other way problem ss
regards
CodePudding user response:
You set the wrong values in the prod.data.json
. You stored numbers as string
.
Set them this way:
{
"products": [
{
"sku" : 10,
"name" : "Laptop Blue Background",
"saleTag" : false,
"prodImage" : "img",
"price" : 210,
"discountly" : 200,
"revives" : 3,
...
CodePudding user response:
That's because prodData
is not an array; it's an object containing a products
array.
Add the wrapper object to your interface:
export interface Inventory {
products: Product[];
}
export interface Product {
...
}
Then in your class:
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
constructor() { }
inventory: Invertory = prodData;
ngOnInit(): void {
}
get products(): Product[] {
return this.inventory.products;
}
}