import { Injectable } from "@angular/core";
import PouchDB from "pouchdb";
@Injectable()
export class AppService {
private settingsDb; //to store app state
constructor() {
// indicates if we are in the process of syncing or not.
this.settingsDb = new PouchDB("field-support-app-state", {
auto_compaction: true
});
}
updateAppState(fields) {
/*
Create a document if it doesnt exist else update it
if creating a new, set all to default then update as
necessary.
Fields is dictionary of fields to update
e.g.
{
'field1':'field1 value'
}
we can update the fields we want only
*/
let vm = this;
const docId = "_local/appState";
this.settingsDb.get(docId, function(err, doc) {
if (err) {
// cant get the info so create the document now with all the fields
console.log("config read error; possibly not found ", err);
let data = { _id: docId };
data["field1"] = "";
data["field2"] = "";
data["field3"] = "";
data["lastNewDataDownloadedDisplayedOn"] = "";
//replace as necessary now
Object.keys(fields).forEach(function(key) {
data[key] = fields[key];
});
vm.settingsDb.put(data);
} else {
// document exists already
// so make changes only then put back the whole document
Object.keys(fields).forEach(function(key) {
doc[key] = fields[key];
});
vm.settingsDb.put(doc);
}
});
}
}
import { Component } from '@angular/core';
import {AppService} from './app.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(
public appSerivce: AppService
) {
this.appSerivce.updateAppState({
lastSyncErrorDisplayedon: ""
})
this.randomUpdates();
}
randomUpdates(){
let fields = ['field1', 'lastUpdatedLocationOn','lastItemMovedOn'];
const vm : any = this;
fields.forEach(field=>{
setInterval(
vm.appSerivce.updateAppState({
field : new Date().toLocaleString()
}) ,
3000);
});
}
}
Immediate conflicts can occur with any API that takes a rev
or a document with _rev
as input – put()
, post()
, remove()
, bulkDocs()
, and putAttachment()
. They manifest as a 409
(conflict) error: