首页 > 解决方案 > 通过服务从 json 文件中获取数据在 Angular4 中给出“意外的输入结束”

问题描述

我正在尝试从位于 assets 文件夹中的 json 文件中获取数据。但反而得到错误。

英雄服务.ts

getPeopleData(): Observable<people[]>{
  return this.http.get<people[]>('assets/data/someData.json');
}

人.interface.ts

export interface people{
    id: number,
    name: string,
    age: number
}

一些数据.json:

[
    {"id":1, "name": "Jack", "age": 21},
    {"id":2, "name": "Rina", "age": 29},
    {"id":3, "name": "Jonathan", "age": 42}
]

about.component.ts

  peopleData:any;

  ngOnInit() {
    this.getPeople();
  }

  getPeople(): void {
   this.heroesService.getPeopleData()
    .subscribe(data => this.peopleData = data)
  }

错误:

在此处输入图像描述

谁能帮帮我,问题出在哪里?相反,控制台中没有错误。

标签: javascriptangularobservableangular-services

解决方案


这对我有用:

服务:

public testJson(): Observable<people[]>{
        return this.http.get("https://api.myjson.com/bins/1f5zag").map(res => res.json());
    }

(您实际上可以使用该网址进行尝试)

组件.onInit

this.yourService.testJson()
    .subscribe( evt => {
      const ppl:people[] = evt;
      console.log(ppl);
    });

推荐阅读