Observables & Promises in Angular 17 - Standalone - UI/UX

Observables and Promises :
            Observables and Promises are both used for handling asynchronous operations in JavaScript, but they have different approaches and use cases. 

Promises :

            Promises were introduced in ES6 (ECMAScript 2015) and provide a way to handle asynchronous operations in a more structured and composable manner than traditional callback functions. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Promises have a few advantages over callbacks:
  • They provide a cleaner and more readable syntax.
  • They can be chained together using .then() and .catch() methods.
  • They handle errors more effectively with the .catch() method.
Observables

            Observables, on the other other hand, are part of the RxJS (Reactive Extensions for JavaScript) library, which implements the Observer pattern. Observables are used for handling streams of data, such as events, asynchronous operations, or multiple data values over time.

Observables have some advantages over Promises:
  • They provide a way to handle streams of data over time, not just a single value.
  • They support operators like map, filter, merge, and combine that allow you to transform and compose observable streams.
  • They can handle cancellation of asynchronous operations more efficiently.
Example : 

Create file called observable.service.ts with the following code :

import { Injectable } from '@angular/core'
import { Observable, of } from 'rxjs'

@Injectable({
    providedIn: 'root'
})

export class ObservableExample{
    getData(): Observable<any> {
        return of({
            name: "Ramesh",
            age: 25
        }).pipe();
    }
}


Then call this is in component.ts file, in following format : 

import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { ObservableExample } from '../services/observable.service';
import { AsyncPipe, NgIf } from '@angular/common';

@Component({
  selector: 'app-observable-example',
  standalone: true,
  imports: [AsyncPipe, NgIf],
  templateUrl: './observable-example.component.html',
  styleUrl: './observable-example.component.css'
})
export class ObservableExampleComponent {

  data$?: Observable<any>;

  constructor(private dataservice : ObservableExample){}

  ngOnInit(){
    this.data$ = this.dataservice.getData();
  }

}

finally this is how you can access this in component.html file : 

<div *ngIf="data$ | async as data">
    <p>Name : {{data.name}}</p>
    <p>Age : {{data.age}}</p>
</div>

Go through this and let me know in the comment section how it is usefull.




Comments

Popular posts from this blog

Finding Second largest number in Array - Java - TCS - Technical Interview

Checking Character only in String - Java 2024 - MNC - Technical Interview

Object Class in Java | Article | Solution Maker - Blog