【发布时间】:2018-04-22 18:36:34
【问题描述】:
这里是 Angular/JavaScript 业余爱好者,正在使用这个框架进行我的第一个项目。我有一个使用服务的组件,该服务对给定的 URL 执行 GET 请求。
组件:
@Component({
selector: 'jive-list',
templateUrl: './jivelist.component.html',
styleUrls: ['./jivelist.component.css']
})
export class JiveListComponent implements OnInit {
JiveLists: String[]; //placeholder
constructor(private JiveListService: JiveListService) { }
getJiveList(): void {
console.log("test");
this.JiveListService.getData().subscribe(
data => console.log(JSON.stringify(data)));
}
ngOnInit() {
this.getJiveList();
//console.log(this.JiveLists) //placeholder
}
}
服务:
@Injectable()
export class JiveListService {
API_URL = environment.JIVEAPIURL //can append endpoints where needed
constructor (public http: HttpClient) {
console.log("constructor runs");
}
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res);
}
}
API URL 目前是一个本地文件,位于 './assets/data/data.json'
此代码实质上是从 URL 获取 JSON 并将其记录在控制台中。当文件是纯 JSON 时,这没有问题。但是,将在生产环境中提供的 JSON 始终以字符串开头。
JSON 示例:
throw 'allowIllegalResourceCall is false.';
{
"id" : "123456",
"resources" : {
//rest of the JSON
我已经尝试了in this article 推荐的两种解决方案,但它们都没有改变我的结果。
示例(尝试)解决方案:
getData(): Observable<any> {
return this.http.get<any>(this.API_URL).map((res) => res.substring(res.indexOf('{')));
}
我的错误信息:
SyntaxError: Unexpected token h in JSON at position 1 at Object.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.bundle.js:43048:37) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2513:31) at Object.onInvokeTask (http://localhost:4200/vendor.bundle.js:75481:33) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:2512:36) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.bundle.js:2280:47) at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.bundle.js:2587:34) at invokeTask (http://localhost:4200/polyfills.bundle.js:3628:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.bundle.js:3654:17)
任何可以帮助我解决此问题的想法将不胜感激。我正在使用 Angular 4.2.4,并使用 @Angular/common/HttpClientModule 作为我的 HTTP 处理程序。
【问题讨论】:
-
你能发布你的整个 json 样本来澄清一些事情吗
-
你在 indexof 之前尝试过类似 res.toString().substring... 和同样的事情。我认为它试图与一个 javascript 对象一起工作,而你的两个函数 indexOf 和 substring 由于这个原因不起作用
-
@qchap 与添加的 toString() 相同的错误
-
@amal 这是一个相当长的 JSON 文件。工作 JSON 文件和产生错误的文件之间的唯一区别是顶部的字符串。
-
可能是地图不喜欢你的资源。您能否尝试正确捕获此问题stackoverflow.com/questions/35326689/… 中的异常。我们也许可以有更多的信息。
标签: javascript json angular http xmlhttprequest