Home > Back-end >  Angular make subscribe to wait for response
Angular make subscribe to wait for response

Time:03-10

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);

CodePudding user response:

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

CodePudding user response:

This is the normal behaviour because your console.log(this.newIds); is outside of the subscription, you just need to move it inside the .subscribe() method:

this.repository.getById(Ids).subscribe((response) => {
      console.log(response);
      this.newIds = response.map((id) => {
        return id;
      });
      console.log(this.newIds);
});

CodePudding user response:

Yes, Because the Javascript is interpreting line-by-line execution so that it will not wait for other processes to complete. That's why the last console will return undefined. In the same time if you use the console inside of the subscriber then you will get proper log because the subscriber will wait for the response and bind it with this.newIds

 this.repository.getById(Ids).subscribe((response) => {
      console.log(response);
      this.newIds = response.map((id) => {
        return id;
      });
     console.log(this.newIds);
    });
  • Related