2017-03-18 118 views
0

我在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"]; 
     }); 
    } 


} 
+4

的[我如何返回從一個異步調用的響應?(可能的複製http://stackoverflow.com/questions/14220321/how-do-i-return-來自異步調用的響應) – echonax

回答

0

你應該做你的邏輯在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 
     }); 
} 
+0

我不工作。我需要保存數組並在所有函數中使用它。 –

+0

只需將其保存在'this.roster_data'或'this.roster'中即可。在構造函數中,你沒有價值,因爲你還沒有得到API的響應。 –

0

通過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"]; 
     }); 
    } 
} 
+0

@ b4rtt - 你對結果的處理取決於你,你必須弄清楚,因爲沒有人知道'playerService'的業務邏輯,但你(你沒有發佈代碼或結果數據契約)。我將它更新爲你所擁有的,基本上完成了這項任務,並將你需要從本地'roster'變量分配給你的組件。 – Igor

+0

非常感謝您的幫助。我添加了我的服務的邏輯。因爲你的代碼仍然不起作用。 –