Reputation: 2593
I am trying to map the Json response to a Typescript class in Angular.
Json Response: [{"id":1,"nodeName":"Root","parentNodeId":null,"value":100.0,"children":[]}]
Although when I run locally I don't see error but the list is still undefined when I try to print on stackblitz, I see below error:
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad
Although I have checked that my Json on Json Lint it is a Valid Json.
Typescript Class:
export class Node {
id?: number;
nodeName?: string;
parentNodeId?: any;
value?: number;
children?: any[];
}
Component.ts Code:
public nodes: Node[];
constructor(private nodeService: NodeService) {}
getAllNodes() {
this.nodeService.getListOfNodes().subscribe((data) => {
console.log('response==>', data);
this.nodes = data;
});
console.log('nodes ====>', this.nodes);
}
StackBlitz Editor Url and StackBlitz Application Url
Upvotes: 1
Views: 1383
Reputation: 1323
Try creating a new folder assets
on the same level as your app
folder, then move the api.json
file into the asset
folder.
Next, modify the node retrieval like this:
getListOfNodes(): Observable<Node[]> {
return this.httpClient.get<Node[]>('/assets/api.json')
}
The nodes should now load.
Upvotes: 2