dAr*_*nac 21 async-await angular
我有一个Angular组件,它可以CatalogService
注入一个服务:
export class CatalogListComponent implements OnInit {
catalog$: Observable<MovieResponseItem[]>;
constructor(private catalogService: CatalogService) {}
ngOnInit() {
this.catalog$ = this.catalogService.userCatalog;
}
}
Run Code Online (Sandbox Code Playgroud)
此服务返回Observable<MovieResponseItem[]>
on属性userCatalog
:
@Injectable()
export class CatalogService {
get userCatalog(): Observable<MovieResponseItem[]> {
return this._userCatalogSubject.asObservable();
}
}
Run Code Online (Sandbox Code Playgroud)
这MovieResponseItem
只是一个简单的界面:
export interface MovieResponseItem {
title: string;
}
Run Code Online (Sandbox Code Playgroud)
现在我想迭代这些项目并显示一个加载动画,同时目录查询底层服务的数据(这需要一些时间) - 这是有效的.这是使用的模板:
<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>
Run Code Online (Sandbox Code Playgroud)
这显然会在异步等待数据时显示#loading模板.如果observable返回数据,则迭代目录值.
但现在我想把它分成这种行为:
我怎么能得到这个?从我在类似帖子上看到的,没有人试图实现这一点(或者我没有找到它).
非常感谢!
bry*_*n60 49
<div *ngIf="catalog$ | async as catalog; else loading">
<ng-container *ngIf="catalog.length; else noItems">
<div *ngFor="let item of catalog">{{item.title}}</div>
</ng-container>
<ng-template #noItems>No Items!</ng-template>
</div>
<ng-template #loading>loading animation...</ng-template>
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题.最好尽可能少地使用同步管道,只需将其声明为"模板变量"即可.否则,每个异步管道将执行一次流,这是一种不好的做法,如果这是http支持,可能会创建不需要的http调用.
*编辑语法错误
归档时间: |
|
查看次数: |
18236 次 |
最近记录: |