En mi servicio tengo esto:
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 }En mi componente:
ngOnInit() { this.myService.getData().then(data => { this.worldCities= data; }); }Debido a que tengo una gran cantidad de datos que recibo de la API, llevará algún tiempo guardarlos todos en IndexedDB. Y cuando cargue la página, el objeto "frutas" estará vacío porque los datos aún no se guardaron en IndexedDB ... Funciona si agrego un tiempo de espera establecido con 2-3 segundos, pero seguramente debería ser una mejor manera para solucionarlo ¿Alguien me puede ayudar con esto? Gracias
Puede considerar agregar un BehaviorSubject a myService .
private synchronized$ = new BehaviorSubject(false);A partir de entonces, debe detectar de alguna manera la finalización de la inserción de ciudades en indexeddb, con algo que probablemente se parezca a
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() }Y luego puede asegurarse de que los datos estén sincronizados antes de acceder a ellos haciendo:
getData(): Promise<any> { return this.synchronized$.pipe( filter(synchronized => synchronized), first(), switchMap(() => from(this.getDataFromIndexedDb())) ).toPromise(); } Lo anterior ciertamente podría hacerse más legible, ya que recomendaría encarecidamente RxJs completos, para evitar cambiar constantemente entre observables y promesas de API, mediante el uso de ngx-indexed-db .