Reputation: 539
I have made two interfaces
export interface IUser {
name: string;
age: number;
address: IAddress
}
export interface IAddress {
city: string;
country: string;
}
Now I am trying to make a mapper service and map the data received in the interfaces and return it.
mapTheData(data): IUser {
let result: IUser;
result.name = data.name;
result.age = data.age;
result.address.city = data.city;
result.address.country = data.country;
return result;
}
Now from a different service file I am calling like this.
getData() {
let mappedData: IUser;
let response = //http call;
mappedData = this.serviceName.mapTheData(response);
return mappedData;
}
after http call, the response I received is
{
name: 'ABC',
age: '20,
city: 'abcd',
country: 'xuasd'
}
When I am doing the above, I get error saying name of undefined, city of undefined.
Please help me.
Upvotes: 0
Views: 1290
Reputation: 6983
Try this.
mapTheData(data: any): IUser {
const result: IUser;
result.name = data.name;
result.age = data.age;
result.address = {
city: data.city,
country: data.country
};
return result;
}
or you can do this.
const mappedUser = <IUser>data;
Upvotes: 1
Reputation: 6488
The address attribute is not defined. Assign the following object to your address attribute:
result.name = data.name;
result.age = data.age;
result.address = {
city: data.city,
country: data.country
};
Upvotes: 0