Back to Blogs

Syncing Couchbase Documents Between Mobile Platforms and Devices with NativeScript and Angular

Nic Raboy of Couchbase Published

Filter blogs by:

Over the past few days we've been exploring how to create a simple Android and iOS application using NativeScript, Angular and Couchbase. First we saw how to use Couchbase for basic key-value operations and then we saw how to query Couchbase as a document database. The final chapter is to add replication support to our NativeScript application using Couchbase Sync Gateway.

We're going to expand upon the previous two examples to synchronize data between platforms and devices using Couchbase Sync Gateway, NativeScript, and Angular. Take the following animated image for example:

Couchbase Sync with NativeScript and Angular

When a new profile is added to the iOS device it is synchronized to the Android device and likewise in the opposite direction. This is possible through very little code.

The Requirements

The requirements between this example and the previous two have changed a bit. To be successful you'll need the following:

NativeScript, Angular, and the Couchbase Lite plugin can all be obtained through the NativeScript CLI. We won't be synchronizing our data to Couchbase Server in this example, but we can easily do so with very little changes.

Picking Up Where We Left Off

To be successful with this tutorial you'll need to have viewed part 2 which has its own dependency of having viewed part 1. Most of the code in those previous guides can be copied and pasted into a project.

Before continuing, you should have a functional two page NativeScript application with a modal dialog. The data in this application is saved in Couchbase and queried using MapReduce views.

Creating an Angular Service for Couchbase

Because data replication will be involved, we need to make sure we only have a single instance of Couchbase running in our application. In the previous example we created a new instance on a per page basis. We can't do that with replication because we may end up replicating multiple times which is inefficient.

To create a singleton instance of Couchbase, we should create an Angular service. Create a file within your project at app/couchbase.service.ts and include the following TypeScript code:

import { Injectable } from "@angular/core";
import { Couchbase } from "nativescript-couchbase";

@Injectable()
export class CouchbaseService {

    private database: any;
    private pull: any;
    private push: any;

    public constructor() { }

    public getDatabase() { }

    public startSync(gateway: string, continuous: boolean) { }

    public stopSync() { }

}

This service will be injectable in every page. A single instance of Couchbase will be stored in the database variable and information about the push and pull replicators will be stored in their respectful variables.

Within the constructor method we have the following:

public constructor() {
    if(!this.database) {
        this.database = new Couchbase("data");
        this.database.createView("profiles", "1", function(document, emitter) {
            emitter.emit(document._id, document);
        });
    }
}

Before creating a new Couchbase instance we make sure we don't already have one. If not, we open the database and create a MapReduce view, which is nothing we haven't already seen in the previous examples.

public getDatabase() {
    return this.database;
}

When it comes time to obtaining this instance we can return it through the getDatabase function. This leads us to data replication.

public startSync(gateway: string, continuous: boolean) {
    this.push = this.database.createPushReplication(gateway);
    this.pull = this.database.createPullReplication(gateway);

    this.push.setContinuous(continuous);
    this.pull.setContinuous(continuous);

    this.push.start();
    this.pull.start();
}

For this example we will do a two-way sync against a Sync Gateway instance. We have the option to sync one time or continuously for as long as the application is open. When we wish to stop replication we can make use of the stopSync function seen below:

public stopSync() {
    this.push.stop();
    this.pull.stop();
}

Since this is going to be a shared service, it needs to be injected into the project's @NgModule block. Open the project's app/app.module.ts file and include the following TypeScript:

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/platform";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { ModalDialogService } from "nativescript-angular/modal-dialog";

import { appComponents, appRoutes } from "./app.routing";
import { AppComponent } from "./app.component";
import { ModalComponent } from "./app.modal";
import { CouchbaseService } from "./couchbase.service";

@NgModule({
    declarations: [AppComponent, ModalComponent, ...appComponents],
    entryComponents: [ModalComponent],
    bootstrap: [AppComponent],
    imports: [
        NativeScriptModule,
        NativeScriptFormsModule,
        NativeScriptRouterModule,
        NativeScriptRouterModule.forRoot(appRoutes)
    ],
    providers: [ModalDialogService, CouchbaseService],
    schemas: [NO_ERRORS_SCHEMA]
})
export class AppModule { }

The above is what we had seen previously, but this time we imported the CouchbaseService and injected it into the providers array of the @NgModule block.

Now each of our pages can be upgraded to use the new Angular service.

Upgrading the NativeScript Application Pages

We have two pages that need to be updated to reflect our Angular service. Open the project's app/components/profile-list/profile-list.ts file and strip out the Couchbase code found in the constructor method. Instead or file should look like the following:

import { Component, OnInit, OnDestroy, NgZone } from "@angular/core";
import { Location } from "@angular/common";
import { Router } from "@angular/router";
import { CouchbaseService } from "../../couchbase.service";

@Component({
    selector: "profile-list",
    templateUrl: "./components/profile-list/profile-list.html",
})
export class ProfileListComponent implements OnInit, OnDestroy {

    public profiles: Array<any>;
    private database: any;

    public constructor(private router: Router, private location: Location, private zone: NgZone, private couchbase: CouchbaseService) {
        this.database = this.couchbase.getDatabase();
        this.profiles = [];
    }

    public ngOnInit() {
        this.location.subscribe(() => {
            this.refresh();
        });
        this.refresh();
    }

    public refresh() {
        this.profiles = [];
        let rows = this.database.executeQuery("profiles");
        for(let i = 0; i < rows.length; i++) {
            this.profiles.push(rows[i]);
        }
    }

    public create() {
        this.router.navigate(["profile"]);
    }

}

Notice in the above that we've imported CouchbaseService and injected it into the constructor method along with NgZone. Instead of getting the database and creating a view, we just need to call the getDatabase function of our service.

Not too bad so far right?

Now let's open the project's app/components/profile/profile.ts file. In this file, include the following code:

import { Component, ViewContainerRef } from "@angular/core";
import { Location } from "@angular/common";
import { ModalDialogService } from "nativescript-angular/directives/dialogs";
import { CouchbaseService } from "../../couchbase.service";
import { ModalComponent } from "../../app.modal";

@Component({
    selector: "profile",
    templateUrl: "./components/profile/profile.html",
})
export class ProfileComponent {

    public profile: any;
    private database: any;

    public constructor(private modal: ModalDialogService, private vcRef: ViewContainerRef, private location: Location, private couchbase: CouchbaseService) {
        this.profile = {
            photo: "~/kitten1.jpg",
            firstname: "",
            lastname: ""
        }
        this.database = this.couchbase.getDatabase();
    }

    public showModal(fullscreen: boolean) {
        let options = {
            context: { promptMsg: "Pick your avatar!" },
            fullscreen: fullscreen,
            viewContainerRef: this.vcRef
        };
        this.modal.showModal(ModalComponent, options).then((res: string) => {
            this.profile.photo = res || "~/kitten1.jpg";
        });
    }

    public save() {
        this.database.createDocument(this.profile);
        this.location.back();
    }

}

With the exception of NgZone, we've made the same change to Couchbase as we did in the previous page. We'll see what NgZone is all about soon.

At this point we can proceed to configuring Sync Gateway in preparation of data synchronization.

Building the Sync Gateway Replication Configuration

You should have already downloaded Couchbase Sync Gateway by now. With it installed we need to create a configuration file for our project. The following is an example of a very simple configuration:

{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
    "databases": {
        "example": {
            "server":"walrus:",
            "sync":`
                function (doc) {
                    channel (doc.channels);
                }
            `,
            "users": {
                "GUEST": {
                    "disabled": false,
                    "admin_channels": ["*"]
                }
            }
        }
    }
}

The above configuration can be saved to a file called sync-gateway-config.json or similar. Essentially it uses an in-memory storage called walrus: with a database name of example. There are no read or write permissions in our example. All data will be synchronized to all platforms and devices.

Connecting the Sync Gateway to Couchbase Server is as simple as changing out walrus: to the host of your Couchbase Server instance.

To run Sync Gateway from the command line you would execute:

/path/to/sync_gateway /path/to/sync-gateway-config.json

It will spin up a dashboard that can be accessed from http://localhost:4985/_admin/. From an application level it will use port 4984.

Including Synchronization Logic for Couchbase and NativeScript

Everything is complete in preparation of data replication in our application. Data replication will allow us to use change listeners to update our UI as needed.

Open the project's app/components/profile-list/profile-list.ts and include the following within the ngOnInit method:

public ngOnInit() {
    this.location.subscribe(() => {
        this.refresh();
    });
    this.couchbase.startSync("http://192.168.57.1:4984/example", true);
    this.database.addDatabaseChangeListener((changes) => {
        for (let i = 0; i < changes.length; i++) {
            let document = this.database.getDocument(changes[i].getDocumentId());
            this.zone.run(() => {
                this.profiles.push(document);
            });
        }
    });
    this.refresh();
}

When the ngOnInit triggers we start synchronization with our locally running Sync Gateway. Feel free to set the hostname to whatever is appropriate for you. After we start syncing, we set up our change listener to push changes into our profiles array. Since this is a listener, we need to use NgZone otherwise it won't reflect in the UI.

The above is only a simple example where we add all changes. In reality you'll need to check if data has changed, was created, or was deleted. All scenarios would come through the addDatabaseChangeListener.

When the application stops, we want to gracefully stop synchronization. In the ngOnDestroy method, include the following:

public ngOnDestroy() {
    this.couchbase.stopSync();
}

Replication to Couchbase Sync Gateway will stop when the above Angular method is called.

Conclusion

In this tutorial you saw how to add synchronization support to your NativeScript Angular mobile application. This was part three of three in the tutorial series. Previously we saw how to do basic Couchbase operations to save and load data as well as query for documents. Data in mobile application development using frameworks like NativeScript and Angular should come easy. Being able to store JavaScript objects and JSON data into a NoSQL database and have it sync is a huge burden lifted for the developer.

«   Back to blogs