如何在服务承诺从数据库返回对象后更新 UI

How to update UI after promise in service returned object from database

我想从 indexed-db 加载一个对象并用 UI 中的数据填写我的表单。我在服务中使用此方法,我的组件在 ngOnInit() 上调用该服务。我的组件如何知道数据是否可用?

service.ts

 private loadFromInMemory(): IConfigEntity {
    this.db.getByKey(this.dbStoreName, 1).then(
      dbContent => {
        console.log(dbContent);
      },
      error => {
        console.log(error);
      }
    );

   return null;
}

component.ts

 ngOnInit() {
    const config = this.configService.load();
    this.testValue = config.test;
    this.test2Value = config.test2;

  }

为您服务return

loadFromInMemory(storename, id) {
    return this.db.getByKey(storename, id);
}

然后在你的组件文件中调用服务函数

constructor (private myservice: ServiceName){}
this.myservice.loadFromInMemory(storename, id).subcribe(
      dbContent => {
        console.log(dbContent);
      },
      error => {
        console.log(error);
      }
    );

rxJs 用于管理状态:

在package.json

"rxjs": "6.2.1",

在役:

import {BehaviorSubject} from 'rxjs/BehaviorSubject';

public onDataChanged: BehaviorSubject<any> = new BehaviorSubject([]);

private loadFromInMemory(): IConfigEntity {
    this.db.getByKey(this.dbStoreName, 1).then(
      dbContent => {
        this.onDataChanged.next(dbContent);
      },
      error => {
        console.log(error);
      }
    );

   return null;
}

在组件中:

import {Subscription} from 'rxjs/Subscription';

private onDataChanged: Subscription;

ngOnInit() {
    this.onUsersListChanged = 
       this.sharedService.onUsersListChanged.subscribe(data => {
         cosnole.log(data) // access to shared data :)
    })
}

public ngOnInit() {
    // Do not forget to unsubscribe the subscription
    this.onDataChanged.unsubscribe();
}