Created
September 27, 2018 04:19
-
-
Save emiliojva/6227913b082b1827bc87de37a9e397bd to your computer and use it in GitHub Desktop.
Ionic/PouchDB. Instalando PouchDB em projeto ionic. Sincronizando e Escutando eventos de sincronização.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Instalando PouchDB em projeto ionic. Sincronizando e Escutando eventos de sincronização com servidor. | |
- Passo 1: Instalando PouchDB no projeto ionic. | |
# npm install pouchdb --save | |
- Passo 2: Instalando @Types do PouchDB, para que o IONIC idenfique-o (Ionic não reconhece o PouchDB). | |
# npm install @types/pouchdb --save | |
*/ | |
import { Component } from '@angular/core'; | |
import { NavController } from 'ionic-angular'; | |
import PouchDB from 'pouchdb'; | |
@Component({ | |
selector: 'page-home', | |
templateUrl: 'home.html' | |
}) | |
export class HomePage { | |
localDB:PouchDB.Database; | |
remoteDB:PouchDB.Database; | |
data: any[] = []; | |
constructor( | |
public navCtrl: NavController | |
) { | |
this.localDB = new PouchDB('documents'); | |
this.localDB.post({ | |
descricao: `esporte`, | |
tipo: `categoria` | |
}) | |
this.remoteDB = new PouchDB('http://ip_server:5984/database_name/', | |
{ | |
auth:{username:`user`,password:`SeCret`} | |
}); | |
let syncHandler = PouchDB.sync(this.localDB,this.remoteDB,{ | |
live:true, | |
retry:true, | |
heartbeat: false, | |
timeout:false | |
}); | |
syncHandler.on('complete',()=>{ | |
console.log(`complete`); | |
}).on('paused', ()=>{ | |
console.log(`paused`); | |
}).on('change',(change:any)=>{ | |
console.log(`change`,change) | |
change.change.docs.forEach(element => { | |
if(element._deleted){ | |
let index = this.data.findIndex( (value)=>{ | |
return value._id = element._id | |
}); | |
this.data.splice(index,1); | |
} | |
}); | |
}); | |
this.localDB.allDocs({include_docs:true}).then( (documents)=>{ | |
documents.rows.forEach(element => { | |
this.data.push(element.doc); | |
console.log(element.doc); | |
}); | |
}) | |
} | |
} | |
/* | |
Referências : | |
# https://www.joshmorony.com/couchdb-pouchdb-and-ionic-2-why-pouchdb/ | |
# https://subvisual.co/blog/posts/130-how-to-build-offline-web-applications-with-couchdb-and-pouchdb/ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment