I want to load an object from indexed-db and fill out my form with this data in the UI. I'm using this method in a service and my component calls the service on ngOnInit(). How does my component know if the data is available?

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;

  }

2 Answers

2
mojtaba ramezani On Best Solutions

Using rxJs for managamant state:

in package.json

"rxjs": "6.2.1",

in service:

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;
}

in component:

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();
}
0
e.k On

In your service return

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

Then in your component file call the service function

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