在Angular中通过订阅服务方法读取json数据

Reading json data through subscription to service method in Angular

我已经研究过其他类似的主题,但对我没有任何帮助。

Players.service.ts

 constructor(private http: Http) {
    }

     getJSON(): Observable<any> {
        return this.http.get('../../assets/players.json')
            .map((res: any) =>  this.players = res.json() )
            .catch((error: any) => Observable.throw( 'error', error));
    }

Player.component.ts

ngOnInit() {
    this.playersService.getJSON().subscribe((players: any[]) => {
    this.players = players; console.log('players ', this.players);
},
     error => console.log(error)
    );
  }

Player.component.html

<app-player-item *ngFor="let player of players"
</app-player-item>

和players.JSON

{
    "players": [
        {
            "name": "xxxx",
            "surname": "xxxxx",
            "city": "xxxxx",
            "ranking": "12",
            "email": "xxxxxx@xxxxx.com",
            "photo": "assets/images/sk.jpg"
        },
        {
            "name": "Sultan Mehmed",
            "level": "Advanced",
            "victories": "18",
            "goalsScored": "23",
            "gamesPlayed": "29",
            "email": "smehmed@ecovadis.com",
            "photo": "assets/images/sm.jpg"
        },
         {....}
         ]
}

应该可以,但我收到以下错误:

  • 'Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as
    Arrays.'
  • Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined TypeError: Cannot read property 'unsubscribe' of undefined

问题出在您的服务 getJson()this.players = res.json() 而非 res.json

你的另一个问题是 ngFor 只适用于数组,所以要么在你的 JSON 文件中使它成为一个实际的数组,要么在你的逻辑中正确定义数组。

I.E.

getJSON(): Observable<any> {
        return this.http.get('../../assets/players.json')
            .map((res: any) => res.json() )
            .map(json => this.players = json['players'])
            .catch((error: any) => Observable.throw( 'error', error));

本质上,第一张地图将您的 json 转换为 json 对象,第二张地图采用 json 并从您的 [=25= 中获取 players 键下的值] 文件并将其映射到您的变量 this.players