如何在使用cordova,ionic 2开发的应用程序中从couchbase lite中检索数据?

时间:2017-01-30 07:07:10

标签: cordova ionic2 couchbase-lite

我正在使用Apache Cordova,离子2开发应用程序。我想在移动设备中使用Couchbase Lite进行本地存储。我认为,能够存储数据。但我无法检索数据。我使用链接https://blog.couchbase.com/2016/december/data-synchronization-with-couchbase-in-ionic-2-hybrid-mobile-apps中给出的示例在Couchbase本地数据库中执行读取和写入操作。

以下是CreateAgent.ts中的代码:

import { Component, NgZone } from '@angular/core';
  import { NavController, AlertController } from 'ionic-angular';
  import { CouchbaseProvider } from "../../app/couchbase-provider";
  import { Toast } from 'ionic-native';
  import "rxjs/add/operator/map";

  @Component({
  selector: 'CreateAgent',
  templateUrl: 'CreateAgent.html'
  })
  export class CreateAgent {
  // declare the variables to hold the values
  firstName: string = "";
  lastName: string = "";
  dateofBirth: any = new Date().toISOString();
  aadharNumber: number;
  panNumber: string = "";
  eMail: any;
  userName: string="";
  mobileNumber: number;
  password: any;
  confPassword: any;
  public items: Array<any>;
  // constructor
  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public couchbase: CouchbaseProvider, public zone: NgZone)
  {
  this.items = []; 
  }

  createAgent()
  {
  let userdetails = {
  "type":"agentdetails",
  "firstName": this.firstName,
  "lastName": this.lastName,
  "dateofBirth": this.dateofBirth,
  "aadharNumber":this.aadharNumber,
  "panNumber":this.panNumber,
  "mobileNumber":this.mobileNumber,
  "userName":this.userName,
  "password":this.password,
  "confPassword":this.confPassword
  };
  this.couchbase.getDatabase().createDocument(userdetails).then((result:any)=>{
  Toast.show("Agent account created.", '6000', 'center').subscribe(
  toast => {
  console.log(toast);
  }); 
  },errors=>
  {
  Toast.show("Failed to create an account for the user.", 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  }); 
  });
  }

  public showAgents() {

  Toast.show("In the show method...", 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  });

  setTimeout(() => {

  this.couchbase.getChangeListener().subscribe(data => {
  for (let i = 0; i < data.length; i++) {
  if (!data[i].hasOwnProperty("deleted") && data[i].id.indexOf("_design") === -1) {
  this.couchbase.getDatabase().getDocument(data[i].id).then((result: any) => {
  if (result.type === "agentdetails") {
  this.zone.run(() => {
  this.items.push(result);
  Toast.show("In the show method..."+result.type, 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  });
  });
  }
  });
  }
  }
  }); 
  }, 100);


  this.couchbase.getDatabase().queryView("_design/todo", "items", {}).then((result: any) => {
  this.items = [];
  for (var i = 0; i < result.rows.length; i++) {
  this.items.push(result.rows[i].value);
  Toast.show("In the query view..."+result.type, 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  });
  }

  Toast.show("Values:"+result.rows[0].value, 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  });

  }, error => {
  console.error("ERROR: " + JSON.stringify(error));
  Toast.show("Error"+JSON.stringify(error), 'long', 'center').subscribe(
  toast => {
  console.log(toast);
  });
  });
  }
  }

在上面的程序中,createAgent()方法用于将代理的详细信息添加到数据库中。 showAgents()方法用于显示创建的代理的详细信息。

CreateAgent.html代码:

<ion-header>
  <ion-navbar color ="secondary">
  <button ion-button menuToggle>
  <ion-icon name="menu"></ion-icon>
  </button>
  <ion-title>Net Zone</ion-title>
  </ion-navbar>
  </ion-header>

  <ion-content padding>
  <h3>Create Agent</h3>
  <ion-list>
  <!--Input box to read the first name the user -->
  <ion-item>
  <ion-label floating>First Name*</ion-label>
  <ion-input type="text" [(ngModel)]="firstName"></ion-input>
  </ion-item>

  <!--Input box to read the last name the user -->
  <ion-item>
  <ion-label floating>Last Name</ion-label>
  <ion-input type="text" [(ngModel)]="lastName"></ion-input>
  </ion-item>

  <!--Read the date of birth from the user -->
  <ion-item>
  <ion-label floating>Date of Birth</ion-label>
  <ion-datetime displayFormat="DD-MMM-YYYY" pickerFormat="DD-MMM-YYYY" [(ngModel)]="dateofBirth"></ion-datetime>
  </ion-item>

  <!--Input box to read the Aadhar number of the user -->
  <ion-item>
  <ion-label floating>Aadhar Number</ion-label>
  <ion-input type="number" [(ngModel)]="aadharNumber"></ion-input>
  </ion-item>

  <!--Input box to read the PAN number of the user -->
  <ion-item>
  <ion-label floating>PAN Number</ion-label>
  <ion-input type="text" [(ngModel)]="panNumber"></ion-input>
  </ion-item>

  <!--Input box to read the email address of the user -->
  <ion-item>
  <ion-label floating>Email</ion-label>
  <ion-input type="mail" [(ngModel)]="eMail"></ion-input>
  </ion-item>

  <!--Input box to choose the username for the user -->
  <ion-item>
  <ion-label floating>Choose your Username</ion-label>
  <ion-input type="text" [(ngModel)]="userName"></ion-input>
  </ion-item>

  <!--Input box to read the mobile number of the user -->
  <ion-item>
  <ion-label floating>Mobile Number</ion-label>
  <ion-input type="number" [(ngModel)]="mobileNumber"></ion-input>
  </ion-item>

  <!--Input box to prompt the user to enter password -->
  <ion-item>
  <ion-label floating>Create Password</ion-label>
  <ion-input type="password" [(ngModel)]="password"></ion-input>
  </ion-item>

  <!--Input box to prompt the user to enter password -->
  <ion-item>
  <ion-label floating>Confirm your Password</ion-label>
  <ion-input type="password" [(ngModel)]="confPassword"></ion-input>
  </ion-item>

  <!--Add button to create the account for the user-->
  <button ion-button secondary (click)="createAgent()">Create User Account</button>

  <button ion-button secondary (click)="showAgents()">Show Agents</button> 
  <ion-item>
  <ion-label>Agent's Details</ion-label> 
  </ion-item>
  <ion-item *ngFor="let item of items">
  {{ item.firstName }}
  </ion-item>

  </ion-list> 

  </ion-content>

但是我的代码没有从本地数据库中检索数据。 请帮助解决问题。我感谢你的帮助。

(编辑:添加其他代码) couchbase-provider.ts代码:

import { Injectable, EventEmitter } from '@angular/core';
  import { Http } from '@angular/http';
  import { Platform } from 'ionic-angular';
  import { Couchbase, Database } from "cordova-couchbase/core";
  import 'rxjs/add/operator/map';

  declare var emit: any;

  @Injectable()
  export class CouchbaseProvider {

  private isInstantiated: boolean;
  private database: Database;
  private listener: EventEmitter<any> = new EventEmitter();

  public constructor(public http: Http, platform: Platform) {
  if(!this.isInstantiated) {
  platform.ready().then(() => {
  (new Couchbase()).openDatabase("netzone").then(database => {
  this.database = database;
  let views = {
  items: {
  map: function(doc) {
  if(doc.type == "list" && doc.title) {
  emit(doc._id, {title: doc.title, rev: doc._rev})
  }
  }.toString()
  }
  };
  this.database.createDesignDocument("_design/todo", views);

  this.database.listen(change => {
  this.listener.emit(change.detail);
  });
  this.database.sync("http://127.0.0.1:4984/_admin", true);
  this.isInstantiated = true;
  }, error => {
  console.error(error);
  });
  });
  }
  }

  public getDatabase() {
  return this.database;
  }

  public getChangeListener(): EventEmitter<any> {
  return this.listener;
  }

  public fetch() {
  return this.database.getAllDocuments.toString();
  }
  }

1 个答案:

答案 0 :(得分:0)

我可以使用以下修改从Couchbase Light获取数据:

更改CreateAgents.ts文件中的showAgents()方法,如下所示:

public showAgents() {
//query the database using the design document and get the results
        this.chitProvider.getDatabase().queryView("_design/agentsDesign", "agents", {}).then((agentsDesignResult: any) => {
            this.agentsArray = [];
            //loop to read the documents as JSON objects and store them in the items array
            for(var i = 0; i < agentsDesignResult.rows.length; i++) {
                this.chitZone.run(() => {
                    this.agentsArray.push(agentsDesignResult.rows[i].value);
                });
 }
            }, error => {
                console.error("ERROR: " + JSON.stringify(error));
            });
    }
}

按如下方式更改CreateAgent.html:

        <!--Button to show all agents account details-->
        <button ion-button secondary (click)="showAgents()">Show Agents</button>        
        <ion-item>
            <ion-label>Agent's Details</ion-label>            
        </ion-item>

        <ion-item *ngFor="let agt of agentsArray">
            <ion-item>{{ agt.fName }}</ion-item>
            <ion-item>{{ agt.lName }}</ion-item>
        </ion-item>

注意:要获取多个值,请将这些键值对详细信息添加到设计文档中的视图中。