nehemia
nehemia

Reputation: 237

Angular2 need to click twice to retrieve JSON and generate HTML

In my template I have a button to trigger the following method:

getResults() {
        this.resultService.getResultsAsTree(this.disk1.id, this.disk2.id, this.mode)
            .subscribe(
                results => this.json = results,
                error => this.errorMessage = <any>error);

        this.getHTML();
    }

The method subscribes to a service which retrieves a JSON object, saves it into the this.json property. Immediately afterwards it will call the this.getHTML() function which should format the JSON into HTML in a tree view through a recursive method:

getHTML() {
        this.html = '';
        this.html += '<div class=\"jstree\"><ul>';
        this.structureAsTree(this.json);
        this.html += '</ul></div>';
    }



    structureAsTree(obj: Object) {
        for (var key in obj) {
            if (!this.isEmpty(obj[key])) { 
                this.html += '<li>' + key + '<ul>';
                this.structureAsTree(obj[key]);
                this.html += '</ul></li>';
            } else {
                this.html += '<li>' + key + '</li>';
            }
        }

    }

Problem

Unfortunately, I have to click the button twice in order to show the rendered HTML. However, from the console I already see that the first click retrieved the JSON object.

I assume that the xhr call is asynchronous and so this.json is empty when the HTML is being created.

Any hint how to resolve this so data is displayed on the first click?

Thanks.

Upvotes: 1

Views: 380

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50643

Solution for your problem:

getResults() {
    this.resultService.getResultsAsTree(this.disk1.id, this.disk2.id, this.mode)
        .subscribe(
            results => this.json = results, // what to do with result
            error => this.errorMessage = <any>error), // what to do if you get error
            () => this.getHTML(); // what to do after you get the result
}

Code after () => is executed after you get data from http request. Http request is asynchronous operation and that's the reason why you can't generate HTML with your current code on the first click - this.getHTML() is called before your request is finished.

Upvotes: 2

Related Questions