2017-01-30 9 views
0

我正在開發一個應用程序使用Apache Cordova,離子2.我想使用Couchbase Lite在移動本地存儲。我認爲,能夠存儲數據。但我無法檢索數據。我使用鏈接https://blog.couchbase.com/2016/december/data-synchronization-with-couchbase-in-ionic-2-hybrid-mobile-apps中給出的示例在Couchbase本地數據庫中執行讀取和寫入操作。如何從使用cordova,ionic 2開發的應用程序中檢索couchbase lite中的數據?

以下是在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(); 
    } 
    } 
+0

你可以添加'couchbaseProvider'代碼嗎? –

+0

@suraj:我添加了couchbase-provider.ts代碼。請檢查。 –

+0

什麼都在日誌中? –

回答

0

我可以使用以下修改得到Couchbase光數據:

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

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> 

注意:要獲取多個值,請將這些鍵值對細節添加到設計文檔中的視圖中。

相關問題