Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
angular load data in component only when indexedDb table is populated

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda