Blog>
Snippets

Reactive Forms with Couchbase Integration

Illustrate the use of Angular reactive forms with real-time Couchbase data synchronization, including form state handling with RxJS.
import { Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { CouchbaseService } from './couchbase.service';

@Injectable({
  providedIn: 'root'
})
export class FormService {
  myForm: FormGroup;

  constructor(private couchbaseService: CouchbaseService) {
    this.myForm = new FormGroup({
      // Initialize your form controls with default values or empty strings
      name: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, Validators.email]),
      message: new FormControl('')
    });

    // Subscribe to changes in the Couchbase document and update the form accordingly
    this.couchbaseService.getDocumentChanges().subscribe(doc => {
      this.myForm.patchValue(doc);
    });
  }

  // Call this method to save the form data to Couchbase
  saveForm() {
    if (this.myForm.valid) {
      this.couchbaseService.updateDocument(this.myForm.value);
    }
  }
}
This code snippet creates a service that encapsulates a reactive form with validation for name and email fields. It subscribes to document changes from Couchbase using the CouchbaseService and updates the form state reactively. The form is also capable of saving valid form data back to Couchbase.
import { Component } from '@angular/core';
import { FormService } from './form.service';

@Component({
  selector: 'app-my-form',
  template: `
    <form [formGroup]='formService.myForm' (ngSubmit)='formService.saveForm()'>
      <input type='text' formControlName='name' placeholder='Name' />
      <input type='email' formControlName='email' placeholder='Email' />
      <textarea formControlName='message' placeholder='Message'></textarea>
      <button type='submit'>Submit</button>
    </form>
  `
})
export class MyFormComponent {
  constructor(public formService: FormService) {}
}
This code snippet defines an Angular component which uses the FormService to display and handle a reactive form with inputs for the name, email, and a message. It binds the form group created in the FormService and defines a submission handler that calls the saveForm method on the form service.
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CouchbaseService {
  // Implement actual Couchbase integration in practice

  // Dummy observable to simulate document changes from Couchbase
  getDocumentChanges(): Observable<any> {
    // Replace with actual listening mechanism to Couchbase's real-time updates
    return of({name: 'John Doe', email: 'john@example.com', message: 'Hello'});
  }

  // Dummy method to simulate document update to Couchbase
  updateDocument(doc: any): void {
    // Replace with actual logic to send data back to Couchbase
    console.log('Document updated', doc);
  }
}
This code snippet is a mock service representing the CouchbaseService. It provides a placeholder getDocumentChanges method that simulates real-time data updates from Couchbase and an updateDocument method to simulate saving data back to Couchbase. The actual implementation would involve the real Couchbase SDK and methods to handle real-time synchronization.