Issue
When I get the data from the json I first create a class and define all the variables I get in json for strict data type like my json file is
{"fname":"Mark","lname":"jhony"}
so in angular i make the class like this
export class user{
fname: string;
lname : string;
}
I am confuse how to make the class for the following json data
{"fname":"Mark","lname":"jhony",
"parcels":[
{
"parcelId":123,
"parcelName :"asd",
"parcelItems:[
{
"itemId":2,
"itemName":"perfume"
},
{
"itemId":4,
"itemName":"soap"
}
]
]}
I tried to add array in the class but not getting what would be the best way to handle it in angularjs.
Solution
Typically you would use an interface to represent a data structure of primitive values, for example:
interface ParcelItem {
itemId: number;
itemName: string;
}
interface Parcel {
parcelId: number;
parcelName: string;
parcelItems: ParcelItem[];
}
interface User {
fname: string;
lname: string;
Parcels: Parcel[];
}
Depending upon how you acquire the JSON and parse it you can specify the interface to use. The most simplistic example would be:
const user = JSON.parse(userJson) as User;
If you want to use a class perhaps for associated methods for data manipulation, you have to instantiate the class using a constructor. This might look like:
const userValues = JSON.parse(userJson);
const user = new User(userValues);
Answered By - Explosion Pills
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.