[英]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.