繁体   English   中英

Angular2服务迭代

[英]Angular2 service iterate

我需要从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();
}

请问失败在哪里?

这应该做您想要的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM