Angular 4异步,加载并显示为空

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调用.

*编辑语法错误

  • 我也不确定你的目录$ observable的源主题是什么,但如果它是一个行为主题,那么这将永远不会"加载",因为值总是立即存在.如果是这种情况,那么你需要将它初始化为null而不是[],因为[]是"truthy",而null是假的 (6认同)