Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular make subscribe to wait for response

I'm trying to subscribe to an Observable and assign some data from the response, but somehow my code it's not waiting for the response. Basically the console.log(this.newIds) is runned first and is always empty because the subscribe doesn't wait for response to come from the backend. How I can force my code to wait for the response to come?

 this.repository.getById(Ids).subscribe((response) => {
      console.log(response);
      this.newIds = response.map((id) => {
        return id;
      });
    });
    console.log(this.newIds);
like image 649
anyway07 Avatar asked Mar 29 '26 02:03

anyway07


1 Answers

If you put the code in the subscribe callback. It will execute after your receive a response from the back-end. All code you write outside this function is directly execute.

     this.repository.getById(Ids).subscribe((response) => {
          //Code will execute when back-end will respond
          console.log(response);
          this.newIds = response.map((id) => {
            return id;
          });
          console.log(this.newIds);
        });
//Code will execute immediately

See also : https://angular.io/guide/observables#creating-observables

like image 133
Pterrat Avatar answered Mar 31 '26 04:03

Pterrat



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!