我有一个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>发布于 2019-03-08 11:16:49
在您的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;
}) 发布于 2019-03-08 11:18:33
编辑您的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>https://stackoverflow.com/questions/55062017
复制相似问题