在我的Angular 6应用程序中。我有一个表,显示来自Web api的数据,也有一些ngIf
容器。如果网络api数据为空,则会显示一条消息。如果有数据返回,另一个应该显示该表。我当前的代码不起作用:
.ts文件
public errorApi = false;
public tableShow = 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');
this.errorApi = data.result == null || data.result === 0 || data.result.length === 0;
this.tableShow = this.data && this.data.result;
})
}
}
html
<ng-container *ngIf="errorApi">
<div class="column col-12 text-center pt-10 pb-10">
<div class="empty">
<div class="empty-icon">
<i class="icon icon-people"></i>
</div>
<p class="empty-title h5">There are no incidents to display</p>
<div class="empty-action">
<button class="btn btn-primary">Create an incident</button>
</div>
</div>
</div>
</ng-container>
<ng-container *ngIf="tableshow">
<table></table>
</ng-container>
答案 0 :(得分:2)
在ngIf语句中尝试 else
<ng-container *ngIf="errorApi else apiTable">
<div class="column col-12 text-center pt-10 pb-10">
<div class="empty">
<div class="empty-icon">
<i class="icon icon-people"></i>
</div>
<p class="empty-title h5">There are no incidents to display</p>
<div class="empty-action">
<button class="btn btn-primary">Create an incident</button>
</div>
</div>
</div>
</ng-container>
<ng-container #apiTable>
<table></table>
</ng-container>
答案 1 :(得分:1)
直接使用data变量检查其是否有数据。
这将检查data
数组中是否有数据。如果有,它将显示该表,但是如果它为空数组或为null,则将显示错误。
首先在ts
中定义数据变量:
data = [];
<div *ngIf="!data.length > 0">
<div class="column col-12 text-center pt-10 pb-10">
<div class="empty">
<div class="empty-icon">
<i class="icon icon-people"></i>
</div>
<p class="empty-title h5">There are no incidents to display</p>
<div class="empty-action">
<button class="btn btn-primary">Create an incident</button>
</div>
</div>
</div>
</div>
<div *ngIf="data.length > 0">
<p>Table Data here</p>
</div>
答案 2 :(得分:1)
尝试使用else
指令中的*ngIf
:
*ngIf="errorApi; else apiTable"
答案 3 :(得分:0)
public data: any;
public loading: boolean;
private subscription: Subscription;
ngOnInit() {
this.loading = true;
this.subscription = this.service.getIncidents(this.customer_id)
.subscribe((data: any) => {
this.loading = false;
// Because you have no error logic in your service
If (data.result //&& any other validation on the data: {}) {
this.data = data.result;
console.log('Result - ', data);
console.log('data is received');
} else {
this.errorApi = true;
}
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
在您的html中,您可以使用ng-template
:
<ng-template *ngIf="data && !loading; else errorTemplate">...</ng-template>
<ng-template #errorTemplate>...</ng-template>
很显然,您需要对数据进行验证:{},但这应该为您提供一些想法。