Angular how to wait for subscribe to finish

Angular: How to wait for subscribe to finish

When working with asynchronous operations, such as HTTP requests in Angular, it is often necessary to wait for the completion of a subscription before proceeding with further operations. This can be achieved using various techniques, including Promises, async/await, or Observable operators. Let’s explore each approach with examples:

Using Promises:


    getData(): Promise<any> {
      return new Promise((resolve, reject) => {
        this.http.get('https://api.example.com/data')
          .subscribe(
            (data) => {
              resolve(data);
            },
            (error) => {
              reject(error);
            }
          );
      });
    }
    
    async fetchData() {
      try {
        const data = await this.getData();
        // Do something with the data
      } catch (error) {
        // Handle error
      }
    }
  

Using async/await:


    async fetchData() {
      try {
        const data = await this.http.get('https://api.example.com/data').toPromise();
        // Do something with the data
      } catch (error) {
        // Handle error
      }
    }
  

Using Observable operators:


    fetchData() {
      this.http.get('https://api.example.com/data')
        .pipe(
          finalize(() => {
            // This code will be executed after the subscription is complete, success or error
          })
        )
        .subscribe(
          (data) => {
            // Do something with the data
          },
          (error) => {
            // Handle error
          }
        );
    }
  

In all these approaches, we wait for the completion of the HTTP request before proceeding with further operations. Choose the one that suits your project requirements and coding style.

Related Post

Leave a comment