Roman Šimr
Roman Šimr

Reputation: 47

Angular2 service iterate

I need to get array from JSON API and then iterate it. I still can't understand how it works. Thank you for help.

This is how looks my service.

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
}

This how I call it

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

Where is the fail please?

Upvotes: 0

Views: 87

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657406

This should do what you want:

@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());
}

Upvotes: 1

Related Questions