首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果api中的数据为0或空,则如何显示消息

如果api中的数据为0或空,则如何显示消息
EN

Stack Overflow用户
提问于 2019-03-08 11:12:47
回答 2查看 5.3K关注 0票数 0

我有一个api的get请求,作为一个服务被调用到我的组件中,如果数据结果为0或空,我想显示一条消息。

Component.ts

代码语言:javascript
复制
 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

代码语言:javascript
复制
  getIn(customerId): Observable<any> {
    return this.http.get<any>(this.serviceApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

html ngif

代码语言:javascript
复制
      <ng-container *ngIf="errorApi">
        <div class="column col-12 text-center pt-10 pb-10">
          <div class="">Error nothing loaded</div>
        </div>
      </ng-container>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-08 11:16:49

在您的subscribe回调中,只需检查是否为data.result == null || data.result === 0 || data.result.length === 0,如果是这样,则将errorApi设置为true

代码语言:javascript
复制
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;
}) 
票数 3
EN

Stack Overflow用户

发布于 2019-03-08 11:18:33

编辑您的component.ts如下,

代码语言:javascript
复制
 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)}

)
        }
    }

这是你的组成部分,

代码语言:javascript
复制
   <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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55062017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档