导入json文件导致HttpClient的解析错误

问题描述 投票:0回答:1

我是学习Angular的新手,对于导入外部数组而言,这似乎是一个简单的解决方案,这导致了一个我根本不理解的错误。我使用过AngularJS并且没有任何这些问题。以下是我收到的错误

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/assets/models.json", ok: false, …}
error
:
{error: SyntaxError: Unexpected token l in JSON at position 10 at JSON.parse (<anonymous>) at XMLHtt…, text: "[↵  {↵    label: "Metal Man",↵    sample: "/assets…es",↵    textures: "6",↵    materials: "1"↵  }↵]↵"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost:4200/assets/models.json"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost:4200/assets/models.json"
__proto__
:
HttpResponseBase

在我的ts文件中,我从资产文件夹中提出以下请求 -

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-work',
  templateUrl: './work.component.html',
  styleUrls: ['./work.component.css']
})
export class WorkComponent implements OnInit {

  viewMode = 'work';
  modelwork: any;


 constructor( private http: HttpClient, public sanitizer: DomSanitizer ) {
 this.sanitizer = sanitizer;
}

ngOnInit(): void {
this.http.get<any>('./assets/models.json').subscribe(
  data => {
    this.modelwork = data;
  })

$(document).ready(function() {
  $(".tag").hide();
  $(".grid-item").hover(function() {
    $(this).children(".tag").stop(true, true).slideToggle(500);
     return false;
  })
});

}
}

我非常想了解导致这个问题的原因,如何解决这个问题,以及是否有任何好的文档可以解决这个问题。我正在使用一本名为ngBook的书来学习我的学习平台以及来自Lynda的视频系列。两者似乎都缺乏关于错误问题的大量信息。我尝试过Git,但我所看到的解决方案对我来说并不合适。我希望从这个错误中吸取教训,并感谢社区提供的任何指导。感谢所有提前回复的人!

json angular compiler-errors http-error
1个回答
1
投票

从错误看起来你的model.json是无效的JSON。尝试在所有键周围加上双引号。

[
  {
    "label": "Metal Man",
    "sample": "/assets…es",
    "textures": "6",
    "materials": "1"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.