Home > Net >  Angular: Map the httpClient Json list response to Typescript Class
Angular: Map the httpClient Json list response to Typescript Class

Time:10-17

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 Error

StackBlitz Editor Url and StackBlitz Application Url

CodePudding user response:

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.

  • Related