在NG2中返回订阅数组没有什么问题。
我是typescript的新手,我不能理解如何在函数和构造函数之间传递变量。
我的代码如下所示:
export class RosterPage extends Page {
roster:Roster[];
players:Players[];
roster_data:any;
constructor(private location: Location, private playersService: PlayersService) {
super(location);
this.players = [];
this.roster = [];
this.roster_data = this.getRoster();
for (let i of this.roster_data) {
console.log(i); // I need iterate
getRoster() {
return this.playersService.getRoster("2017","MUZ").subscribe(roster => {
this.roster = roster["soupiska"];
});
}
}发布于 2017-03-18 21:47:53
通读How do I return the response from an asynchronous call?。它将回答如何处理异步调用的基本问题,如从服务器获取数据或向服务器推送数据。
OnInit,并将你想要在load上执行的数据访问移动到那里,而不是在构造函数中。代码
// import OnInit
import {OnInit} from '@angular/core';
// implement OnInit
export class RosterPage extends Page implements OnInit {
roster:Roster[] = [];
constructor(private location: Location, private playersService: PlayersService) {
super(location);
}
// start any async/server calls from ngOnInit, NOT the constructor
ngOnInit() {
this.loadRoster();
}
// loads data from the service
loadRoster() {
// starts an async call to the service to get the rosters
this.playersService.getRoster("2017","MUZ").subscribe(roster => {
// once the call completes you have access to the data
// this is a callback
// you now have access to the data
// copy what you need to your component/page (whatever it is) using this.xxxx
this.roster = roster["soupiska"];
});
}
}发布于 2017-03-18 21:20:14
你应该在getRoster()函数中做你的逻辑。
export class RosterPage extends Page {
roster:Roster[];
players:Players[];
roster_data:any;
constructor(private location: Location, private playersService: PlayersService) {
super(location);
this.players = [];
this.roster = [];
this.roster_data = this.getRoster();
getRoster() {
return this.playersService.getRoster("2017","MUZ").subscribe(roster => {
this.roster = roster["soupiska"];
for (let i of this.roster) console.log(i); // I need iterate
});
}https://stackoverflow.com/questions/42874857
复制相似问题