Data come from API, but does not display. Angular 9 ABP framework

Viewed 289

I want to populate data in my select control which is placed in the header child component, but data comes from the API, but it does not display.

Enter image description here.

  ngOnInit() {
    this._assingedSiteService.getAssignedSitesForLogInUser().subscribe(
      (res) => {
        this.sites = res;
        console.log(this.sites);
      },

      (error) => {
        console.log(error);
      }
    );
  }
<li class="nav-item">
  <select class="form-control">
    <option *ngFor="let site of sites">
      {{site.siteName | json}}
    </option>
  </select>
</li>

1 Answers

You need to wait for the received data before rendering the page. You can do two things:

  1. Use a boolean and ngIf directive so:

     loadingData = true;
     ngOnInit() {
         this._assingedSiteService.getAssignedSitesForLogInUser().subscribe((res) => {
             this.sites = res;
             console.log(this.sites);
             this.loadingData = false;
           }, (error) => {
             console.log(error);
           }
         );
     }
    

    Template

       <select class="form-control" *ngIf="!loadingData">
         <option *ngFor="let site of sites">
           {{site.siteName | json}}
         </option>
       </select>
    
  2. Which I prefer, if you have no logic inside your subscription, use async pipe inside your template:

     sites$: Observable<Site>;
    
     ngOnInit() {
        this.sites$ = this._assingedSiteService.getAssignedSitesForLogInUser();
     }
    

    Template:

       <select class="form-control">
         <option *ngFor="let site of sites$ | async">
           {{site.siteName | json}}
         </option>
       </select>
    
Related