0
votes

I am developing an app that is requesting user information from an API.

In the 'list-all'component, ngOnInit is getting only the IDs and users names to show all in a list.

When I click in username I need to expand and load the rest of users information. But the problem is that the views is rendering before the data is fully loaded.

Tryed this:

solution1: If I create another component and do the load on ngOnInit, it works, but I dont want to create another component.

solution2: Using BehaviorSubject to control when the data is loaded, it works fine. But everytime when I click on another user the subscribe function calls one time more than the last time. For the first one, he calls everything in subscribe function only 1 time, the second 2 times, and so goes on.

How can I know when the data is fully loaded?

I dont know if you guys can understand my doubt, hope you will. But any questions comment on this.

Function in service

 carregaObservacoes(avId: number, colabId: number) {
    this.observacoesCarregadas.next(false);
    this.http.request(this.host + '/observacoes/' +
      avId + '/' + colabId)
      .map(res => res.json())
      .subscribe(obs => {
        this.observacoes = obs;
        this.observacoesCarregadas.next(true);
      });
  }

In component

this.observacaoService.carregaObservacoes(this.avaliacao.id , colabId);
    this.observacaoService.observacoesCarregadas.subscribe(estado => {
      if (estado) {
        this.observacoes = this.observacaoService.getObservacoes();
        this.compilaObservacao();
        this.etapa = success;
      }
    });
1

1 Answers

-1
votes

Angular Data resolver to the rescue !

You can use it as below :

Define a resolver :

@Injectable()
class TeamResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    return this.backend.fetchTeam(route.params.id);
  }
}

Define it in your route config

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

And get the Data in your component using :

this.route.data.pluck('team').subscribe(team => this.team = team).

The component will not render until the data is resolved !