首页 > 解决方案 > 在 Angular 中重新渲染视图模板的差异 Observable 等待和 setTimeout

问题描述

我有排序数据的本地存储,这可能需要一段时间:

private store: IBacktest[] = [];

public setStore(content: string): Observable<void> {
    return new Observable<void>((observer) => {
            this.store = content
                .trim()
                .split('\n')
                .map(item => toTestCase(item))
                .sort((a, b) => b.profitToDropDown - a.profitToDropDown);
            observer.next();
            observer.complete();
        }
    );
}

元素的数量 5000 - 10000 并且它得到 10 - 30 秒,因为toTestCase,这不是一个便宜的操作。我想渲染加载器一个更用户友好的界面:

this.isLoader = true;
this.backtestService
    .setStore(content)
    .pipe(finalize(() => {
        this.isLoader = false;
    }))
    .subscribe(() => {...});

<app-loading-overlay *ngIf="isLoader"></app-loading-overlay>在模板中。

但是什么时候isLoader = true我可以在调试模式下看到它加载覆盖而不是渲染。

但是当我尝试setTimeout()像这样测试它的逻辑时:setTimeout(() => { this.isLoader = false; }, 100000)一切正常并且加载器是可见的。

我的可观察使用有什么问题,以及如何在没有多余的包装纸setTimeout()或类似拐杖的情况下解决它?

标签: angulartypescriptrxjs6angular2-observables

解决方案


我认为这里的问题isLoader是没有更新他在 DOM 中的值。

让我们尝试使用get/set我们知道他们会更新他们的价值。

private _isLoader: boolean = false;
public get isLoader() {
   return this._isLoader;
}
public set isLoader(value: boolean) {
   this._isLoader = value;
}
callsetStore(): {
   this.isLoader = true;
   this.backtestService
    .setStore(content)
    .pipe(finalize(() => {
        this.isLoader = false;
    }))
    .subscribe(() => {...});
}

然后在html中:

<app-loading-overlay *ngIf="isLoader"></app-loading-overlay>

有了这个,我认为它应该知道。尝试一下,如果它不起作用,我们将尝试另一种方法。


推荐阅读