【发布时间】:2018-03-08 03:23:24
【问题描述】:
我有一个 Angular 组件,它获得了 CatalogServiceinjected 服务:
export class CatalogListComponent implements OnInit {
catalog$: Observable<MovieResponseItem[]>;
constructor(private catalogService: CatalogService) {}
ngOnInit() {
this.catalog$ = this.catalogService.userCatalog;
}
}
此服务在属性userCatalog 上返回Observable<MovieResponseItem[]>:
@Injectable()
export class CatalogService {
get userCatalog(): Observable<MovieResponseItem[]> {
return this._userCatalogSubject.asObservable();
}
}
MovieResponseItem只是一个简单的界面:
export interface MovieResponseItem {
title: string;
}
现在我想迭代项目并显示加载动画,同时目录查询底层服务的数据(这需要一些时间) - 这很有效。这是使用的模板:
<div *ngIf="(catalog$ | async)?.length > 0; else loading">
<ng-container *ngFor="let item of catalog$ | async">
<div>{{item.title}}</div>
<ng-container>
</div>
<ng-template #loading>loading animation...</ng-template>
这显然会在异步等待数据时显示#loading 模板。如果 observable 返回数据,它会遍历目录值。
但现在我想把它分成这种行为:
- 在等待数据时,显示加载动画
- 如果我们有来自服务的响应并且返回的列表为空,请显示信息文本(如“您的目录为空”)并且不要迭代(因为没有数据)
- 如果我们有来自服务的响应并且返回的列表有值,则迭代项目(与当前状态一样)
我怎样才能做到这一点?根据我在类似帖子上阅读的内容,没有人试图实现这一目标(或者我没有找到)。
非常感谢!
【问题讨论】:
-
您可以在您的 ngFor 容器下方添加另一个
<ng-container *ngIf="catalogService.userCatalog.length == 0"> <div>your catalogue response is empty</div> <ng-container>。
标签: angular async-await