Gaurav Pathak
Gaurav Pathak

Reputation: 2593

Angular: Map the httpClient Json list response to Typescript Class

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);
}

Error

StackBlitz Editor Url and StackBlitz Application Url

Upvotes: 1

Views: 1383

Answers (1)

Andrew Halil
Andrew Halil

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

Related Questions