Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: Using HttpClient.get.toPromise

From a service constructor, I want to call 2 HttpClient.get asynchronously. When the constructor is completed, the 2 get requests have to be already completed.

public async ReadConfiguration () 
  {
      await this.http.get ('http://localhost:80/api/Target.xml',{ responseType: 'text' })
        .toPromise()
        .then(res => console.log(res))
        .catch(err => { console.log ('error');
        });

      console.log ('line 25');

      await this.http.get ('http://localhost:80/api/Target.xml',{ responseType: 'text' })
        .toPromise()
        .then(res => console.log(res))
        .catch(err => { console.log ('error');
        });

      console.log ('line 32');
  }

  /*************************************************************************************/
  constructor(private http: HttpClient) {
    console.log ('-->constructor');
    this.ReadConfiguration ();
    console.log ('Done');
    console.log ('<--constructor');

  }

On the console I got:

-->constructor <br/>
Done <br/>
<--constructor <br/>

and only then (after few constructors are executed) I got the data.

Can you please tell what is wrong in my code ?

Thank you in advance, Zvika

like image 454
Zvi Vered Avatar asked Jun 21 '26 15:06

Zvi Vered


1 Answers

The purpose of using the constructor is to create the component and to initiate the variables

In your case you are looking for what we called it a 'HOOK' as ngOnInit that is executed after the Constructor.

Please look at this : Difference between Constructor and ngOnInit

And For the Synchronicity which may depends on the response time of your API i suggest you to make the two calls as a nested call, i mean one can be inside the other as bellow :

await this.http.get ('http://localhost:80/api/Target.xml',{ responseType: 'text' })
        .toPromise()
        .then(res => {

 await this.http.get ('http://localhost:80/api/Target.xml',{ responseType: 'text' })
        .toPromise()
        .then(res => console.log(res))
        .catch(err => { console.log ('error');
        });

})
        .catch(err => { console.log ('error');
        });
like image 76
Youssef Tounoussi Avatar answered Jun 23 '26 03:06

Youssef Tounoussi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!