无法正确读取json文件

时间:2020-06-16 13:57:43

标签: javascript angular8

我是新来的,找不到任何问题的答案,或者可能是我没有以正确的方式查找。我昨天开始实习,这是我第一次使用Angular。目前,我正在读取json文件并获取一些信息,但是我使用语法进行了测试并且可以正常工作,但是服务器发送的文件有些不同。我一直在测试这个json文件(不是公司的文件)

[
    {"name": "Justine", "age": 25, "sexe": "femme"},
    {"name": "Alex", "age": 23, "sexe": "homme"}
]

但是,如果我将[变成{,它将不再起作用

{
    {"name": "Justine", "age": 25, "sexe": "femme"},
    {"name": "Alex", "age": 23, "sexe": "homme"}
}

提前谢谢!

编辑:这是组件的代码

import { InformationsService } from '../informations.service';

@Component({
  selector: 'app-info',
  template: `<h2> Liste </h2>
    <ul *ngFor="let f of info"> 
      <li>{{f.name}} <br></li>
    </ul>`,
  styles: []
})
export class InfoComponent implements OnInit {
  public info = [];

  constructor(private _info : InformationsService) { }

  ngOnInit() {
    this._info.getInfo().subscribe(data => (this.info = data));
  }

}

服务代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Info } from './informations';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InformationsService {

  private _url: string = "/assets/data/file.json";
  constructor(private http : HttpClient) { }
  getInfo(): Observable<Info[]>{
    return this.http.get<Info[]>(this._url);
  }
}

我忘了说我的文件来自API,没有[,只有{

1 个答案:

答案 0 :(得分:0)

您需要将数据放入json的根属性中

{
   "root": [
        {"name": "Justine", "age": 25, "sexe": "femme"},
        {"name": "Alex", "age": 23, "sexe": "homme"}
       ]
}