gpt4 book ai didi

javascript - Angular2 服务迭代

转载 作者:行者123 更新时间:2023-12-03 04:41:16 26 4
gpt4 key购买 nike

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

关于javascript - Angular2 服务迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com