Promises 
Promises  are typically used for asynchronous operations that will complete once and produce a single value (or an error). A common use case in Angular is fetching data from an API.

 

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

 

interface User{
 userId: number;
 id: number;
 title: string;
 completed: boolean;
}

@Component({
 selector: 'app-promise',
 template: ``,
})


export class PromiseComponent implements OnInit {
 todo: Todo | null = null;
 error: string | null = null;
 loading: boolean = false;

 constructor(private http: HttpClient) {}

 ngOnInit(): void {  
   this.getUsers();
 }

 

 getUsers(): void {
   this.loading = true;
   this.http.get<User>('api_url')
     .toPromise()  // Convert the Observable returned by HttpClient to a Promise
     .then(data => {
       this.user= data;
       this.loading = false;
       this.error = null;
     })
     .catch(err => {
       this.error = 'Failed to fetch todo.';
       this.loading = false;
       this.todo = null;
       console.error(err);
     });
 }
}

 

 

 

Observables 
Observables are useful for handling streams of data over time, such as real-time updates, user input, or repeated events.

import { Component } from '@angular/core';
import { interval, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
 selector: 'app-observable',
 template: `
   <h2>Observable Emitting Values</h2>
   <p>Current value: {{ value$ | async }}</p>
 `,
})
export class ObservableComponent {
 value$: Observable<string>;

 constructor() {
   this.value$ = interval(1000).pipe(
     map(count => `Elapsed seconds: ${count}`)
   );
 }
}

This creates an Observable that emits a sequential number (0, 1, 2, ...) every 1000 milliseconds (1 second).

 

 

Difference

  • Promise: Represents a single asynchronous operation that will eventually produce a single result or an error. You typically use .then() for success and .catch() for errors.
  • Observable: Represents a stream of data that can emit zero, one, or multiple values over time, and may or may not complete. You subscribe to an Observable to receive these emitted values and handle errors and completion.

Related Question