【问题标题】:How to retrive data from the couchbase lite in an app developed using cordova, ionic 2?如何在使用cordova,ionic 2开发的应用程序中从couchbase lite检索数据?
【发布时间】:2017-02-07 17:38:33
【问题描述】:

我正在使用 Apache Cordova,ionic 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();
  }
  }

【问题讨论】:

  • 可以加couchbaseProvider代码吗?
  • @suraj:我添加了 couchbase-provider.ts 代码。请检查。
  • 日志中有什么内容?
  • 没有错误。我使用 toast 消息来了解流程。控件进入showAgents()方法,但没有进入里面的for循环或者错误部分。
  • 我建议您尝试使用更简单的代码版本。您正在设置一个带有超时的更改侦听器。您如何更改数据以触发侦听器?您的循环中有几个测试。你确定他们是正确的吗?我真的建议先写一份文档,然后再读一遍并确保它包含您所期望的内容。然后从那里建立你的逻辑。

标签: cordova ionic2 couchbase-lite


【解决方案1】:

我可以通过以下修改从 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>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2017-09-03
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多