使用Angular和PouchDB进行PWA

时间:2018-12-27 21:11:52

标签: angular pouchdb

我已经使用了Angular Heroes tutorial,并且正在尝试实现pouchdb服务来提供数据。我已经备份了原始的英雄服务,该服务提供了一系列具有不同属性的英雄。我现在正在尝试修改服务以从本地pouchdb中提取文档。我已经修改了HeroService类,并在构造函数中设置了一些选项。

import { Injectable, EventEmitter  } from '@angular/core';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import { Observable, of } from 'rxjs';
import {MessageService} from './message.service';
import PouchDB from 'pouchdb';

@Injectable({
  providedIn: 'root'
})

export class HeroService {
  private isInstantiated: boolean;
  private database: any;
  private listener: EventEmitter<any> = new EventEmitter();


  constructor(private messageService:MessageService) { 
    if(!this.isInstantiated) {
      this.database = new PouchDB("http://server:5984/db1");
      this.isInstantiated = true;
  }
}



  getHeroes(): Observable<Hero[]> {
  console.log(this.database.allDocs({include_docs: true}))
    return of(this.database.allDocs({include_docs: true}));
    this.messageService.add("HeroService: fetched heroes");

    };

console.log在console.log行的hero.service.ts文件中显示“ ZoneAwarePromise”,但具有要在屏幕上显示的数据和文档数组。我是否使用服务将PouchDB中的数据提供给Angular应用程序,采取了正确的方法?

我要显示此数据的组件是“ dashboard.components.ts”文件,这是新功能:

getHeroes(): void {
    console.log(this.heroes)
    console.log(this.heroService.getHeroes());
    this.heroService.getHeroes()
    .subscribe(heroes => this.heroes = heroes);
    //console.log(this)

  }

是否有更好的方法?

1 个答案:

答案 0 :(得分:0)

可以说,您错过了Pouch的两个最酷的优点……离线优先和后台实时更新

要获得前者,您应该实例化两个数据库:一个远程数据库,另一个local to the browser本身。然后,您可以在两者之间设置复制。第一次运行后,根本没有网络连接,您的页面将像联机一样工作。对本地数据库的写入和读取将是瞬时的。重新联机后,Pouch将透明地同步所有本地和远程数据。 This article可能会帮助您入门(尽管您可以忽略有关Phoenix的内容;您可以直接连接到CouchDB)。

如果您还使用 live-find ,则屏幕数据将在几秒钟内更新,以向用户显示服务器端的更改,而无需您进行其他特殊编程。

最后,我建议您评估Couchbase(使用复制网关)而不是CouchDB,它似乎是后起之秀,而CouchDB似乎已不受欢迎。