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

时间:2018-03-05 01:20:45

标签: json angular http subscription

我已经完成了其他类似的主题,但没有任何方法可以帮助我。

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"
        },
         {....}
         ]
}

应该可以工作,但我得到错误:

  
      
  • &#39;错误:无法找到不同的支持对象&#39; [object Object]&#39;类型&#39;对象&#39;。 NgFor仅支持绑定到Iterables,例如
      阵列&#39;
  •   
  • 未捕获(承诺):TypeError:无法读取属性&#39;取消订阅&#39;未定义的TypeError:无法读取属性   &#39;取消订阅&#39;未定义的
  •   

1 个答案:

答案 0 :(得分:0)

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

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

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并从json文件中获取players键下的值并将其映射到变量this.players