Search code examples
angularrxjsionic4

I call an array in a function and it is void, why?


This is my .ts code :

array:any = [];

OnClickFunction(){
    
    this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'})
          .subscribe(data => {
            this.array = data;
            console.log(this.array)// This array contain many data
          });

    console.log(this.array)// this call of this array contain nothing, why ???

Solution

  • This is a perfect place to demonstrate the async pipe and how it can manage subscriptions to observables for you.

    array$: Observable<any[]>;
    
    OnClickFunction(){
      this.array$ = this.httpClient.get<any[]>("http://url/?lbs="+this.my variable,{responseType: 'json'});
    }
    

    and in your template you use

    <ng-containter *ngIf="array$ | async as array">
        {{ array | json }} Inside here you have your array available
    </ng-container>