Roman Šimr
Roman Šimr

Reputation: 47

Typescript Subscribe method return

I have little problem with returning subscribe array in NG2.

I am newbie in typescript and I can't understand how to transfer vars between functions and constructor.

My code looks like this:

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


}

Upvotes: 0

Views: 1833

Answers (2)

Igor
Igor

Reputation: 62213

Read through How do I return the response from an asynchronous call?. It will answer the basic question on how to deal with async calls like getting or pushing data from/to a server.

  • You should implement OnInit and move data access you want to perform on load there and not in the constructor.
  • I removed the parts that were extranious and did nothing to add to your problem. This makes for a more clear illustration as to what is actually happening.

code

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

Upvotes: 1

Matej Maloča
Matej Maloča

Reputation: 974

You should do your logic in getRoster() function.

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

Upvotes: 0

Related Questions