Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda