Angular2服务迭代

时间:2017-03-28 18:16:07

标签: javascript angular typescript

我需要从JSON API获取数组然后迭代它。我仍然无法理解它是如何工作的。谢谢你的帮助。

这就是我服务的方式。

import {Injectable} from '@angular/core';
import { Http } from "@angular/http";
import "rxjs/Rx";

@Injectable()
export class PlayersService {
    roster:Roster[];

    constructor(private http: Http){
        this.roster = [];
    }


    getPlayer(id) {
       for (let player of this.roster) {
            console.log(player["id"]);
        }   
    }


    getRoster(season,category) {
        this.roster.push(this.http.get("http://API JSON LIST OF ID")
            .map(res => res.json()));
    }

}

interface Roster {
    id:number
}

我怎么称呼它

ngOnInit() {
   this.getRoster();
   this.getPlayers();
}

请问哪里失败?

1 个答案:

答案 0 :(得分:1)

这应该做你想要的:

@Injectable()
export class PlayersService {
    roster:Roster[];

    constructor(private http: Http){
        this.roster = [];
    }

    getPlayer(id) {
       for (let player of this.roster) {
            console.log(player["id"]);
        }   
    }

    getRoster(season,category) {
        return this.http.get("http://API JSON LIST OF ID")
       .map(res => res.json())
       .do(val => this.roster.push(val));  // the do operator should be used for side effects (eg modifying an existing array)
    }
}
ngOnInit() {
   this.playerService.getRoster().subscribe(val => this.playerService.getPlayer());
}