Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70435

Setting instance variables in constructor and observables - "this" is unknown

$
0
0

@Bschuhma wrote:

Hi everyone :slight_smile: ,

Hopefully this is a noob question about promises/observables and instance variables…

Having difficulties in a constructor that opens an XML file (via http get), parses it to JSON and trying to save the resulting JSON for later use. All usages of xml2js I see merely log the result of the xml2js and doesn’t really do anything with it.

export class Election {
public xml: string = “”;
public jsonObj: string = “”;
public BallotItems: BallotItem[];
public Contests: Contest[];
public myhttp: Http;

public edfFile: string;

//take a filename, parse it to json, then build subordinate objects (Contests, BallotItems, etc.)
constructor(_http: Http, aString: string) {
    this.myhttp = _http;
    if (null != aString) {
        this.edfFile = aString;

        try {

            let jsonData;
            let xmlData;
            this.myhttp.get(this.edfFile).map(res => res.text()).subscribe(data => {
                this.xml = data.toString();   //  <<<<<<<<<  doesn't throw an error, but doesn't persist,either
                xmlData = data.toString();
                parseString(xmlData, function (err, jsonData) {
                    this.jsonObj = jsonData;  //<<<<<<<  "this" is unknown at this point
                    this.setContests();   //<<<<<<<<<<<  "this" is unknown at this point
                    // this.getBallotItems(); //<<<<<<<<   "this" is unknown at this point
                });
            });


        } catch (e) {
            console.log("Error:", e);
        }
    }
}

I’m getting the XML and I see the JSON parsed from it, but I can’t save the JSON.

My goal is to save the result of the JSON from parseString to the instance variable jsonObj (i.e. this.jsonObj) so I can query it later and create other objects based on certain parts of the JSON.

I’m getting a runtime error:
TypeError: Cannot set property ‘jsonObj’ of undefined

I’m assuming it’s because the object itself hasn’t been defined because it’s in the constructor.

I’m rather new to Observables, Promises, etc… I’m coming from a Java background where you process something and it happens immediately (i.e. not something to be eventually processed and returned later maybe), so I’m having a hard time figuring out when my variables get populated so I can use them. :frowning:

Thanks for your insights,

Bret

Posts: 2

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70435

Trending Articles