代码之家  ›  专栏  ›  技术社区  ›  Deadpool

通过服务从json文件获取数据“输入意外结束” 角度4

  •  0
  • Deadpool  · 技术社区  · 7 年前

    英雄服务.ts

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

    people.interface.ts

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

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

    关于.component.ts

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

    enter image description here

    有人能帮帮我吗,哪里出了问题?控制台中没有错误。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jacopo Sciampi    7 年前

    这对我有用:

    服务:

    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);
        });