我有一个api的get请求,作为服务调用到我的组件中,如果数据结果为0或为空,我想显示一条消息。
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>
答案 0 :(得分:2)
在您的subscribe
回调中,只需检查data.result == null || data.result === 0 || data.result.length === 0
,然后将errorApi
设置为true
。
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;
})
答案 1 :(得分:2)
按如下所示编辑您的component.ts,
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)}
)
}
}
这是您的组件方面,
<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>