In my service I have this:
synchronizeCitiesOnLogin() {
....
this.getCitiesFromApi().subscribe(
cities => {
cities.map((city) => {
this.addCityToIndexedDb(city);
});
}
);
}
getCitiesFromApi() {
....
return this.apiClient.get(url, { })
.pipe(
map((response: any) => response.data ),
catchError(errorRes => {
return throwError(errorRes);
})
);
}
addCitiesToIndexedDb(city) {
this.cityTable
.add(city)
.then(async () => {
const allItems: CityModel[] = await this.cityTable.toArray();
})
.catch(e => {
alert('Error: ' + (e.stack || e));
});
}
getData(): Promise<any> {
return this.getDataFromIndexedDb()
}
private async getDataFromIndexedDb() {
...
...
return mydata
}
In my component:
ngOnInit() {
this.myService.getData().then(data => {
this.worldCities= data;
});
}
Because I have a lot of data that I receive from the API it will take some time to save all of them in the IndexedDB. And when I load the page the "fruits" object will be empty because the data were not saved yet in the IndexedDB ... It's working if I'm adding a settimeout with 2-3 seconds but for sure it should be a better way to solve it Can somebody help me with this ? Thank you
You can consider adding a BehaviorSubject to myService.
private synchronized$ = new BehaviorSubject(false);
Thereafter you need to somehow catch the completion of cities insertion into indexeddb, with something looking propably like
import { from } from 'rxjs';
synchronizeCitiesOnLogin() {
this.getCitiesFromApi().pipe(
switchMap((cities) => combineLatest(
cities.map(city => from(this.cityTable.add(city)))
)),
tap(() => {
this.synchronized$.next(true);
})
).subscribe()
}
And then you can ensure data is synchronized before accessing it by doing:
getData(): Promise<any> {
return this.synchronized$.pipe(
filter(synchronized => synchronized),
first(),
switchMap(() => from(this.getDataFromIndexedDb()))
).toPromise();
}
The above could certainly be made more readable, as I would strongly suggest to go full RxJs, to avoid constantly switching between observables and promise api, by using ngx-indexed-db.