【发布时间】:2021-12-04 01:23:17
【问题描述】:
我正在尝试将 Json 响应映射到 Angular 中的 Typescript 类。
Json 响应:[{"id":1,"nodeName":"Root","parentNodeId":null,"value":100.0,"children":[]}]
虽然我在本地运行时没有看到错误,但是当我尝试在 stackblitz 上打印时列表仍然未定义,我看到以下错误:
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad
虽然我在Json Lint 上检查了我的 Json,但它是一个有效的 Json。
打字稿类:
export class Node {
id?: number;
nodeName?: string;
parentNodeId?: any;
value?: number;
children?: any[];
}
Component.ts 代码:
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);
}
【问题讨论】:
-
如果您将原始 JSON 字符串打印到控制台而不调用
JSON.parse,它会是什么样子? -
@j_m4rtinez 我无法将
直接转换为字符串,因为它会给出错误,所以我已更改为 类型并且出现错误:ERROR SyntaxError: Unexpected token o in JSON at position 1 在 JSON.parse ( ) -
您的模拟数据文件是
api/api.json,但您尝试请求的 URL 是api/api-data.json(在您的 NodeService 类中)。尝试使它们相同。 -
@j_m4rtinez 感谢您的注意,我可能在复制和粘贴时出错了。我已经更正了,但我仍然有问题,不知道我还在犯什么错误。
-
与您在上面的屏幕截图中发布的错误完全相同吗?
标签: json angular typescript angular-httpclient