1

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

7
  • What does your raw JSON string look like if you print it to the console without calling JSON.parse? Commented Oct 15, 2021 at 23:31
  • @j_m4rtinez I cannot convert <Node[]> to string directly as it gives error, so I have changed to <any> type and there is error: ERROR SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) Commented Oct 15, 2021 at 23:50
  • Your mock data file is api/api.json but the URL you are trying to request from is api/api-data.json (in your NodeService class). Try making them the same. Commented Oct 16, 2021 at 0:17
  • @j_m4rtinez Thanks for noticing, I might have made mistake while copy and pasting. I have corrected it but I am still having issue, not sure what mistake I am still making. Commented Oct 16, 2021 at 0:22
  • is it the same exact error as the one posted in your screenshot above? Commented Oct 16, 2021 at 0:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.