Typescript订阅方法返回
我在NG2中返回subscribe数组的问题很少。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"];
});
}
}
你应该做你的逻辑在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
});
}
我不工作。我需要保存数组并在所有函数中使用它。 –
只需将其保存在'this.roster_data'或'this.roster'中即可。在构造函数中,你没有价值,因为你还没有得到API的响应。 –
通过How do I return the response from an asynchronous call?来阅读。它将回答关于如何处理异步调用的基本问题,如从服务器获取数据或向服务器推送数据。
- 您应该实现
OnInit
并移动要加载的数据访问权限,而不是在构造函数中。 - 我删除了外挂的部件,并且没有为您的问题添加任何内容。这就为实际发生的事情提供了更清晰的说明。
代码
// 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"];
});
}
}
@ b4rtt - 你对结果的处理取决于你,你必须弄清楚,因为没有人知道'playerService'的业务逻辑,但你(你没有发布代码或结果数据契约)。我将它更新为你所拥有的,基本上完成了这项任务,并将你需要从本地'roster'变量分配给你的组件。 – Igor
非常感谢您的帮助。我添加了我的服务的逻辑。因为你的代码仍然不起作用。 –
的[我如何返回从一个异步调用的响应?(可能的复制http://*.com/questions/14220321/how-do-i-return-来自异步调用的响应) – echonax