首页 > 解决方案 > 无法正确读取 json 文件

问题描述

我是新来的,我没有找到任何问题的答案,或者也许我没有以正确的方式查找。我昨天开始实习,这是我第一次使用 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 并且没有 [,只有 {

标签: javascriptangular8

解决方案


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

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

推荐阅读