Search code examples
javascriptangularasynchronousrxjsobservable

How to do things after an observable gets its data in Angular


I am using an observable to retrieve data from an http like:

handleError(error:any) {
...
}
getData() {
   return this._api_service.http.get<JSON>(this._url).pipe(retry(1), catchError(this.handleError));
}
loadData() {
    this.getData().subscribe((data: {}) => {
        do_something_to_data(data);
    });
    // here I want to do somethings after all the data are loaded
    do_other_work();
    // what should I do here?
}

It seems do_other_work will get called before do_something_to_data is called. What should I change?

I tried next, pipe, but seems not working or observable does not support next().


Solution

  • The reason that do_other_work() is called before do_something_to_data() is because Observable are asynchronous by nature. To make sure that do_other_work() is called after the data is loaded and processed, you should call it inside the subscribe() method, after the do_something_to_data() call.

    Placing do_other_work() inside the subscribe() method, will ensure that it is called after do_something_to_data() has been executed, and the data is fully loaded/processed.

    loadData() {
        this.getData().subscribe((data: {}) => {
            // Pass the data to the do_something_to_data() function
            do_something_to_data(data);
            do_other_work();
        });
    }
    

    And like Austin said, You could also pass the data as an argument to do_something_to_data() function, assuming that the function accepts the data as an input parameter.