2016-10-22 48 views

回答

2

我开始阅读Josh Morony这篇文章真的有帮助! (谢谢乔希伟大的职位!)。我的设置是为了cloudant,虽然它应该与couchdb相同。

让我总结一下我为香草角2设置了什么,请随时参阅Josh的帖子,以获取下面几点的详细描述。我假设你已经有一个云帐户和一个数据库创建(如果没有,你可能想从那里开始)。

  1. npm install pouchdb --save
  2. npm install -g typings
  3. typings install --global --save dt~pouchdb dt~pouchdb-adapter-websql dt~pouchdb-browser dt~pouchdb-core dt~pouchdb-http dt~pouchdb-mapreduce dt~pouchdb-node dt~pouchdb-replication

注:下cloudant请确保您启用了数据库API CORS。

安装上述所有之后,我们需要改变一些文件(见下文):

  1. 角cli.json - 修改“套餐”数组以反映以下:

    "packages": [ 
    { 
        "PouchDB": { 
        "main": "pouchdb.js", 
        "defaultExtension": "js" 
        } 
    }] 
    
  2. 创建例如 “DataService的”(我用angular-cli)新的 “服务”,您可以复制粘贴。他们在这里的关键是“require(pouchdb)”,从而使其可以通过导入访问其他组件。

    import { Injectable } from '@angular/core'; 
    var PouchDB = require('pouchdb'); 
    
    @Injectable() 
    export class DataService { 
    
        db: any; 
        username: any; 
        password: any; 
        remote: any; 
        data: any; 
    
        constructor() { 
        this.db = new PouchDB('YOUR_DATABASE'); 
        this.username = 'DATABASE_KEY'; 
        this.password = 'YOUR_PASSWORD'; 
    
        this.remote = 'https://YOU_ACCOUNT_NAME.cloudant.com/YOUR_DATABASE'; 
    
        let options = { 
         live: true, 
         retry: true, 
         continuous: true, 
         auth: { 
         username: this.username, 
         password: this.password 
         } 
        }; 
    
        this.db.sync(this.remote, options); 
    
        } 
    
        // other CRUD functions below... 
    } 
    
  3. app.module.ts - 导入新的 “DataService”,并把它添加到 “providers”。

  4. 现在你已经准备好开始玩了。例如,在您的主页组件下,导入“DataService”并开始调用您的CRUD功能,例如getDocuments,AddDocument等。

注意:如果你要通过邮差(例如)要测试你的API,请确保您在“授权”输入您的cloudant/CouchDB的登录/密码。否则,您将遇到读取错误的权限。

演示应用程序:https://github.com/rrubio/Angular2PouchDdCloudant

+0

您不认为ts文件中的存储数据库凭据不安全吗? –

+0

没错!如果你想要有一个外部应用程序,你需要在中间使用类似expressjs的东西。 –