Skip to content Skip to sidebar Skip to footer

Reading An Environment Variable Before It Is Defined

I am using an environment variable to be able to read something from a JSON and display in my HTML. My issue is that my HTML is trying to read the environment variable before it ha

Solution 1:

Change your variable like this:

id: any;

also change your template like this:

<p>Player One is: {{ id?.playerone }} </p>

Another version of the above code [a bit better]:

import { HttpClient } from'@angular/common/http';

exportclassApComponentimplementsOnInit {
    id$: Observable<any>;

    constructor(private httpService: HttpClient) { }
    ngOnInit() {
        this.id$ = this.httpService.get('http://server/info.json')
                       .pipe(
                          catchError((error) => {
                             //handle your errorconsole.log(error);
                          })
                        )
        );
    }
}

Now change your template to make use of async pipe like this:

<ng-conatiner *ngIf="(id$ | async) as id"><p>Player One is: {{ id.playerone }} </p></ng-container>

NOTICE - you are not subscribing to the observable in your component. async pipe is taking care of subscription management [i.e. subscribing/unsubscribing.].

Post a Comment for "Reading An Environment Variable Before It Is Defined"