Angular 4异步加载并在空时显示 [英] Angular 4 async with loading and display when empty

查看:66
本文介绍了Angular 4异步加载并在空时显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular组件,该组件获得了注入CatalogService的服务:

I have an Angular component that gets a service 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只是一个简单的界面:

The MovieResponseItemis just a simple interface:

export interface MovieResponseItem {
  title: string;
}

现在,我想对项目进行迭代并显示加载动画,同时目录查询基础服务以获取数据(这需要一些时间)-这可行.这是使用的模板:

Now I want to iterate the items and display a loading animation while the catalog queries the underlying service for data (that takes some time) - this works. This is the template used:

<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模板.如果观察到的返回数据,则对目录值进行迭代.

This obviously displays the #loading template while the async is awaiting data. If the observable returns data, it iterates over the catalog values.

但是现在我想将其分为以下行为:

But now I want to separate this into this behaviour:

  • 等待数据时,显示加载动画
  • 如果我们收到该服务的响应,并且返回的列表为空,请显示信息文本(例如您的目录为空"),并且不要进行迭代(因为没有数据)
  • 如果我们收到了服务的响应,并且返回的列表中包含值,请对项目进行迭代(与当前状态一样)

我该如何实现?根据我在类似帖子上看到的内容,没有人试图实现这一目标(或者我没有找到它).

How can I achive this? From what I read on similiar posts nobody tried to achieve that (or I did not find it).

非常感谢!

推荐答案

 <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>

这应该可以解决问题.最好使用尽可能少的异步管道,并仅将其声明为可以在任何地方使用的模板变量".否则,该流将在每个异步管道中执行一次,这是一种不好的做法,如果使用HTTP支持,则可能会创建不需要的HTTP调用.

This should do the trick. Better to use as few async pipes as possible and just declare it "as" a template variable you can use where ever. Otherwise the stream will be executed once per async pipe which is a bad practice and could create unneeded http calls if this is http backed.

*编辑语法错误

这篇关于Angular 4异步加载并在空时显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆