-1

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 ???
Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
  • 1
    Because `.get()` is async operation and its result can only be accessed inside the observable's callback. – Tsvetan Ganev Jun 23 '20 at 21:00
  • 1
    Answer: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular – R. Richards Jun 23 '20 at 21:13
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – rhavelka Jun 23 '20 at 21:27

2 Answers2

0

Here is what Tsvetan Ganev said in picture form:

enter image description here

The numbers demonstrate the order of operation.

#1. The code issues an http get request, which is asynchronous.

#2. The line after the subscribe is executed and the console logs that the local variable is currently undefined.

#3. At some later point in time, when the asynchronous call returns the response, then the code within the subscribe (the callback) is executed and the response data is assigned to the local variable.

Hope this helps.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
0

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>
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Thank you ! So I would like to use the json data first in the .ts before displaying it in the html, I tried console.log (array.string), array [string], array ['string'], array [int ], in short, I cannot display json data, could you help me ? – Patrice Blanchard Jun 24 '20 at 05:09
  • use a map function `httpClient('url').pipe(map(resp => functionThatModifiesResponse(resp))` – Adrian Brand Jun 25 '20 at 01:22