Blog>
Snippets

Subscribing to Couchbase Real-time Data Changes in Angular

Showcase how to subscribe to data changes in Couchbase and reflect them in real-time in an Angular component using RxJS.
import { Injectable } from '@angular/core';
import { Couchbase } from 'nativescript-couchbase-plugin';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CouchbaseService {
  private database: any;

  constructor() {
    this.database = new Couchbase('my-database-name');
  }

  getChangeListener(): Observable<any> {
    return new Observable((observer) => {
      const listener = this.database.addDatabaseChangeListener((_changes) => {
        observer.next(_changes);
      });
      return () => this.database.removeDatabaseChangeListener(listener);
    });
  }
}
CouchbaseService is an injectable Angular service that initializes a connection to a Couchbase 'my-database-name' database and provides an Observable to subscribe to for real-time data changes using the 'addDatabaseChangeListener' method.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CouchbaseService } from './couchbase.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-real-time-updates',
  template: '<div *ngFor="let item of items">{{item | json}}</div>'
})
export class RealTimeUpdatesComponent implements OnInit, OnDestroy {
  items = [];
  private changesSubscription: Subscription;

  constructor(private couchbaseService: CouchbaseService) {}

  ngOnInit(): void {
    this.changesSubscription = this.couchbaseService.getChangeListener().subscribe(changes => {
      this.items = [...this.items, ...changes.documents];
    });
  }

  ngOnDestroy(): void {
    if (this.changesSubscription) {
      this.changesSubscription.unsubscribe();
    }
  }
}
RealTimeUpdatesComponent is an Angular component that subscribes to the observable provided by the CouchbaseService to receive real-time updates of the Couchbase database. It updates the 'items' array which is used in the template to display the data. The subscription is set up in 'ngOnInit' and cleaned up in 'ngOnDestroy' to prevent memory leaks.