1

I want to show some html code based on response,but HTML render before receive response.

Html:

 <div *ngIf="medias.length > 0">
    some text
 </div>

<div *ngIf="!medias.length > 0">
    some other text
</div>

Ts:

ngOnInit(): void {
    this.getMedias();
}

medias: Array<T> = [];

getMedias() {
   this.controllerApiService
   .getById()
   .subscribe(data => {
     this.medias = data
   });
}

According to the code above firstly show "some other text" and after receive response,show "some text"

I trying to handle with skip() and skipWhile() but nothing change.

Random
  • 3,158
  • 1
  • 15
  • 25
heliya rb
  • 682
  • 8
  • 26

1 Answers1

6

Multiple problems here.

First, use RxJS to its full potential. Then, use Angular to its full potential too. Finally, use the correct conditions to make it all work.

<ng-container *ngIf="medias$ | async as medias">

  <div *ngIf="medias.length; else noMedia">
    Some media : {{ medias.length }}
  </div>

  <ng-template #noMedia>
    No media
  </ng-template>

</ng-container>

medias$ = this.getMedias().pipe(shareReplay(1));

getMedias() {
  return this.controllerApiService.getById();
}

MGX
  • 2,534
  • 2
  • 14
  • What is the use of shareReplay(1) here? – heliya rb Jan 03 '23 at 11:20
  • `shareReplay` is used to avoid redoing the http call at every new subscription. In that particular case I don't think this is useful, but I got the habit of putting it almost everywhere just for safety, I would suggest you do the same – MGX Jan 03 '23 at 12:32