簡體   English   中英

Typescript訂閱方法返回

[英]Typescript Subscribe method return

我在NG2中返回訂閱數組沒什么問題。

我是打字稿的新手,我不明白如何在函數和構造函數之間傳遞var。

我的代碼如下所示:

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 
       });
}

通讀我如何從異步調用返回響應? 它將回答有關如何處理異步調用(如從服務器獲取數據或將數據推送到服務器)的基本問題。

  • 您應該實現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"];
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM