RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. RxJS Observables are used to do synchronous or callback-based code (like events, promises, or AJAX). They also improve performance as emit values without changing the reference of object.

Observables will notice the change without creating reference. So we can subscribe to the Observables and on change manually run change detector inside subscribe method to change view.

RxJS Applications in Angular

RxJS are used in various application ins Angular.

  1. HTTP requests (HttpClient)
  2. Forms (ReactiveForms)
  3. Routing (ActivatedRoute)
  4. Component communication (e.g., Subject)
  5. State management (e.g., NgRx)


Use Observables

To use RxJS Observables, import BehaviorSubject in component. Observables can change the value but the new reference is not created.

           <!--app.component.html-->

  <h1>{{title}}</h1>
  <button (onclick)="changeTitle()">Click</button>
  <p>{{data._value}}</p>


           <!--app.component.ts-->
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  changeDetection:ChangeDetectionStrategy.OnPush,
})
export class AppComponent {

  title = 'myApp'; 

  x=0;
  data:any;

  ngOnInit(){
    this.x=10;
    this.data=new BehaviorSubject(this.x);
  }

  changeTitle(){
    this.x=this.x+this.x;
    this.data.next(this.x);
  }
 
}