相关疑难解决方法(0)

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

我有一个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返回数据,则迭代目录值.

但现在我想把它分成这种行为:

  • 当我们等待数据时,显示加载动画
  • 如果我们有来自服务的响应并且返回的列表为空,则显示信息文本(例如"您的目录为空")并且不进行迭代(因为没有数据)
  • 如果我们有来自服务的响应并且返回的列表具有值,则迭代项目(如当前状态)

我怎么能得到这个?从我在类似帖子上看到的,没有人试图实现这一点(或者我没有找到它). …

async-await angular

21
推荐指数
1
解决办法
2万
查看次数

标签 统计

angular ×1

async-await ×1