Blog>
Snippets

Implementing Offline-First with Angular and Couchbase

Provide an example of implementing offline-first functionality in an Angular application using Couchbase Mobile.
import { CouchbaseLite } from '@capacitor-community/couchbase-lite';

@Injectable({
  providedIn: 'root'
})
export class DatabaseService {
  private databaseName = 'app-database';

  constructor() { }

  /**
  * Initialize the Couchbase Lite database
  */
  async initDatabase(): Promise<void> {
    try {
      await CouchbaseLite.init();
      console.log('Couchbase Lite initialized successfully');
    } catch (error) {
      console.error('Couchbase Lite initialization failed', error);
    }
  }

  /**
  * Create a new document or update an existing one
  */
  async saveDocument(doc: any): Promise<void> {
    try {
      const result = await CouchbaseLite.createDocument({
        database: this.databaseName,
        data: doc
      });
      console.log('Document saved successfully', result);
    } catch (error) {
      console.error('Failed to save document', error);
    }
  }
}
This code provides an Angular service called DatabaseService. It includes methods to initialize the Couchbase Lite database and to save a document to the database. It uses the @capacitor-community/couchbase-lite package for Couchbase Lite integration with Angular.
import { Component } from '@angular/core';
import { DatabaseService } from './database.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'offline-first-app';

  constructor(private dbService: DatabaseService) {
    this.initApp();
  }

  async initApp() {
    // Initialize the database when the app starts
    await this.dbService.initDatabase();
  }

  async saveOfflineData(data: any) {
    // Save data to local database for offline access
    await this.dbService.saveDocument(data);
  }
}
This code provides an Angular component called AppComponent that uses the DatabaseService to initialize the Couchbase Lite database on app start and provides a method to save data for offline access.