如何解决加载..不显示的问题。
这是代码: HTML
<div *ngIf="tempThermometer | async as temp; else loading">
<ng-container *ngIf="temp.length !== 0; else noItems">
<div *ngFor="let item of temp">
{{temp.sensor}}</div>
</ng-container>
<ng-template #noItems>No Items!</ng-template>
</div>
<ng-template #loading>loading animation...</ng-template>
TYPESCRIPT
tempThermometer = new BehaviorSubject<any>([]);
async getRoomList() {
this.subscription = await this.global
.getData(`/conditions/latest`)
.pipe(take(1))
.subscribe((res: any) => {
this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
return {
...obj,
spinning: true
};
})));
console.log(this.tempThermometer.value);
});
}
我想做的是在获取数据的同时显示加载情况。
这里的问题是加载...不显示它自动显示无数据!
最佳答案
您的问题是 BehaviorSubject
是用 []
初始化的,因此 *ngIf="tempThermometer | async
将始终为 true。您必须检查其长度是否为 0,但我看到您检查了其长度是否为 0 并显示 No Items!
尝试:
<ng-container *ngIf="!tempLoading">
<div *ngIf="tempThermometer | async as temp">
<ng-container *ngIf="temp.length !== 0; else noItems">
<div *ngFor="let item of temp">
{{temp.sensor}}
</div>
</ng-container>
<ng-template #noItems>No Items!</ng-template>
</div>
</ng-container>
<div *ngIf="tempLoading">loading animation...</div>
tempLoading = false; // new variable to show loading or not, can initialize it to true depending on your use case
tempThermometer = new BehaviorSubject<any>([]);
getRoomList() { // remove async, nothing async about this function
this.tempLoading = true;
this.subscription = this.global
.getData(`/conditions/latest`)
.pipe(take(1))
.subscribe((res: any) => {
this.tempThermometer.next(Object.values(res['data'].map((obj: any) => {
return {
...obj,
spinning: true
};
})));
this.tempLoading = false; // set the loading to false
console.log(this.tempThermometer.value);
});
}
关于javascript - 如何修复加载不以 Angular 显示的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60517843/