Angular 2-在尚未解决(observableData | async)时显示加载信息 [英] Angular 2 - Show loading-information when (observableData | async) is not yet resolved

查看:78
本文介绍了Angular 2-在尚未解决(observableData | async)时显示加载信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我想拥抱rxjs Observables的力量.

just as the title says, I want to embrace the power of rxjs Observables.

我现在要做什么:

// dataview.html
<div *ngIf="isLoading">Loading data...div>
<ul *ngIf="!isLoading">
    <li *ngFor="let d of data">{{ d.value }}</li>
</ul>


// dataview.ts

data: any[] = [];
isLoading: boolean = false;

getData() {

this.isLoading = true;
this._api.getData().subscribe(
        data => {
            this.data = data;
            this.isLoading = false;
        },
        error => {
            this.error = error;
            this.isLoading = false;
        });
}

我想做什么:

1.在模板中使用async管道

1. Use async pipe in my template

  1. 使data一个可观察的数组

仍然为用户显示加载信息

Still display loading information for the user

我非常喜欢干净的代码,那么如何使用rxjs和Angular 2很好地做到这一点?

I'm a big fan of clean code, so how can this be done nicely using rxjs and Angular 2?

推荐答案

这就是我的方法.另外,我在变量名称的和处使用$来提醒我,它是一个流.

This is how I do it. Also i use $ at the and of the variable name to remind me that it is a stream.

// dataview.html
<div *ngIf="isLoading$ | async">Loading data...</div>
<ul *ngIf="!(isLoading$ | async)">
    <li *ngFor="let d of data">{{ d.value }}</li>
</ul>


// dataview.ts

data: any[] = [];
isLoading$: BehaviorSubject<boolean> = new BehaviorSubject(false);

getData() {

this.isLoading$.next(true);

this._api.getData().subscribe(
        data => {
            this.data = data;
        },
        error => {
            this.error = error;
        },
        complete => {
            this.isLoading$.next(false);
        });
}

这篇关于Angular 2-在尚未解决(observableData | async)时显示加载信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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