Before reading this article, please go through my previous articles for better understanding,
- Basics Of Angular And Its Versions - Part One
- Basics Of Angular And Its Versions - Part Two
- Basics Of Angular And Its Versions - Part Three
- Basics Of Angular And Its Versions - Part Four
To deal with asynchronous data Angular provides two models of approaches, we can either use Promises or Observables.
Promises
- Emits a single value
- Cannot be canceled
- Not Lazy
Even after we comment the then() method but the service call still be issued to the web API call over the network. In order to get the data from service call we have to handle it using then() method.
- Supports async/await
- Easy readable source code when we use try/catch & async/await
- Promises require the caller to have access to the original function that returned the promise in order to have a retry capability.
By default, Angular built-in HTTP services return Observable. To return Promise as a response to the called method, first, we have to convert the response to Promise using toPromise() method.
Sample code snippet for Promise call,
- request(req: Request): Promise<any> {
- return this.http.request(req)
- .toPromise()
- .then((response: Response) => {
- return response.text().length ? response.json() : null;
- })
- .catch((error: any) => this.handleError(error, req));
- }
To support toPrimise() method, first we have to import toPromise() from rxjs as below,
import 'rxjs/add/operator/toPromise';
Observables
- Emits multiple values over a period of time.
We can think of an observable like a stream which emits multiple values over a period of time and the same call back function is called for each item emitted. So, with an observable, we can use the same API to handle asynchronous data whether the data is emitted a single value or multiple values over a period of time.

Join the conversation! Your thoughts help the community grow.