Roka545
Roka545

Reputation: 3636

Make HTML wait for value from HttpGet method.

I'm displaying data to HTML based on the value of a variable which is set during an HTTP call. The HTTP call doesn't return data immediately - some authentication steps occur first before my value ('this.activeEvent') is set. Because of this, sometimes my program will throw an error because 'this.activeEvent' is still null even though the call has already happened - it just hasn't returned a value yet. How do I go about making my HTML wait until the value is set?

Here's how I subscribe:

getActiveEvent() { console.log('Home:getActiveEvent entered...');

this._eventService.getActiveEvent()
    .subscribe(res => {
        this.activeEvent = res;
    });

}

and here's the actual call:

getActiveEvent() { console.log('EventService:getActiveEvent entered...');

return this._http.get('/test/events/activeevent')
    .map((response) => {
        console.log(response.json());
        return response.json();
    });

}

Here's my HTML - it prints a field of this.activeEvent:

<div class="panel panel-default" style="border-color: #464646;">
    <div class="panel-heading" style="border-color: #BBBBBB; height: 35px; padding-top: 3px;">
        <div style="float: left; margin-top: 5px;">Active Event NAme{{activeEvent.Name}}</div>
    </div>
</div>

Upvotes: 0

Views: 60

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

Show the div only if activeEvent is defined:

<div *ngIf="activeEvent" ...>

Or use

activeEvent?.Name

Upvotes: 3

Related Questions