Sole
Sole

Reputation: 3340

Angular how to display a message if data from api is 0 or empty

I have a get request from an api, called in as a service into my component, I would like to display a message if the data result is 0 or empty.

Component.ts

 public errorApi = false;


 ngOnInit() {
    this.service.getIncidents(this.customer_id).subscribe((data) => {
      this.loading = true;
      this.data = data.result;
      this.loading = false;
      console.log('Result - ', data);
      console.log('data is received');
    })
    }
}

Service.ts

  getIn(customerId): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

html ngif

      <ng-container *ngIf="errorApi">
        <div class="column col-12 text-center pt-10 pb-10">
          <div class="">Error nothing loaded</div>
        </div>
      </ng-container>

Upvotes: 0

Views: 7262

Answers (2)

Pac0
Pac0

Reputation: 23129

In your subscribe callback, just check if data.result == null || data.result === 0 || data.result.length === 0, and set errorApi to true if this is the case.

this.service.getIncidents(this.customer_id).subscribe((data) => {
  this.loading = true; // ?? off-topic, but this seems nonsense, you should set it to true, before the subscribe
  this.data = data.result;
  this.loading = false;
  console.log('Result - ', data);
  console.log('data is received');

  errorApi = data.result == null || data.result === 0 || data.result.length === 0;
}) 

Upvotes: 3

rcanpahali
rcanpahali

Reputation: 2643

Edit your component.ts like below,

 public errorApi = false;


     ngOnInit() {
        this.service.getIncidents(this.customer_id).subscribe(
       (success) => {
          this.loading = true;
          this.data = success.result;
          this.loading = false;
          console.log('Result - ', data);
          console.log('data is received');
        },
       (error) => {
         this.errorApi = true;
         console.log('Error state from API:,' error)}

)
        }
    }

And this is your component side,

   <ng-container *ngIf="!data">
    <div class="column col-12 text-center pt-10 pb-10">
          <div class="">Error nothing loaded</div>
        </div>
      </ng-container>
      <ng-container *ngIf="errorApi>
       <p>API error happened.</p>
      </ng-container>

Upvotes: 2

Related Questions