I am new to Angular and I am trying to map the returned json to my interface but failed.
Here's the link to the code I have.
You dont need to use map since you response is object and as i see you want to map data property from that.
One way to do it would be
getTestData(): Observable<TestObject>{
const url = 'https://api.myjson.com/bins/11x4bx';
// return this.http.get(url).pipe(
// map(response => ((response || {} as any).data || []).map(testData => this.mapTest(testData))));
return this.http.get(url).pipe(
map((resp: any) => {
return <TestObject> {
id: resp.data.id,
view: resp.data.view,
resourceName: resp.data.resourcename,
loadCapacity: resp.data.loadcapacity
}
})
);
}
Cleaner way
getTestData(): Observable<TestObject>{
const url = 'https://api.myjson.com/bins/11x4bx';
return this.http.get(url).pipe(pluck('data'));
}
When you are not sure about how to build an interface for your response, you can use JSON2TS
declare module namespace {
export interface Meta {
entityName: string;
}
export interface Data {
id: string;
view: string;
startdate: string;
enddate: string;
erp: string;
loadcapacity: string;
userid: string;
resourceid: string;
resourcename: string;
userdatalimitationid: string;
requestleaveforself: boolean;
bookforself: boolean;
lastmodified: string;
}
export interface RootObject {
meta: Meta;
data: Data;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With