在所有异步http调用完成之前,如何显示加载指示器-Angular

时间:2018-10-09 14:51:06

标签: html angular typescript asynchronous dynamic

我的问题是如何显示加载微调框,直到所有异步HTTP请求都完成为止。这样,在从服务器接收到所有数据之前,我不会显示屏幕上的点点滴滴。

我最大的问题是,我的组件是通过html专门触发的,所以当我想显示它时,不能简单地在整个html上放置*ngIf语句。

这是我到目前为止所拥有的。仅供参考,当此组件中的一个http请求完成时,将设置当前触发html可见性的Template变量。在显示html之前,我想等待子组件的http请求完成,但是我必须在html中执行逻辑才能调用子组件。

*ngIf语句目前不能按我希望的方式工作,不能,我只是在显示我当前正在做的事情。

<div class="col-sm-12"
            *ngIf="Template">
    <div id="nav" style="height: 200px">
        <div id="outer"
             style="width: 100%">
            <div id="inner">
                <o-grid>
                </o-grid>
            </div>
        </div>
    </div>
    <collapsible-panel *ngFor="let s of Template?.s; let i = index"
                       [title]="s.header">
        <div *ngFor="let c of s.c">
            <fact [eC]="c.c"
                    [label]="c.l">
            </fact>
        </div>
    </collapsible-panel>

    <collapsible-panel title="T">
        <div>
            <i-f >
            </i-f>
        </div>
    </collapsible-panel>
</div>
<div *ngIf="!Template" class="spinner"></div>

编辑(解决方案):这是我实施的解决方案,根据@ danday74的以下答案。

我实例化了服务内部的变量,在该变量中发出了所有的http请求。我将其定义为true开始,并在订阅完成时在其中一个子组件中将其设置为false。

我只需要确保将来将最后一个异步http请求发生的地方的cService.asyncRequestsInProgress设置为false,就可以了。

父HTML:

<div class="col-sm-12"
             [ngClass]="{hideMe:cService.asyncRequestsInProgress}">
    ......
</div>
<div *ngIf="cService.asyncRequestsInProgress" class="spinner"></div>

服务:

@Injectable()
export class CService {

    asyncRequestsInProgress: boolean = true;
    constructor(public http: HttpClient) { }
}

子组件(最后一个异步请求完成的地方):

export class FComponent implements OnInit {
    ....
    doSomething() {
        this.cService.getWhatever().subscribe(x => {
            this.cService.asyncRequestsInProgress = false;
        }
    }
}

styles.css

.hideMe {
  visibility: hidden;
}

2 个答案:

答案 0 :(得分:1)

您可以使用解析器。解析器确保在加载组件之前先加载数据。

或者,如果您不想使用* ng,则可以只使用[ngClass]="{hideMe: allAsyncRequestsComplete}"设置样式,直到加载完成才显示。 CSS可能是:

.hideMe {
  visibility: hidden;
}

加载完成后,将allAsyncRequestsComplete设置为true。

答案 1 :(得分:0)

您可以使用解析器进行加载,然后在app.component.ts中,根据事件将变量设置为true或false:

navigationInterceptor(event: RouterEvent): void {
  if (event instanceof NavigationStart) {
    //true
  }
  if (event instanceof NavigationEnd) {
    //false
  }

  // Set loading state to false in both of the below events to hide the spinner in case a request fails
  if (event instanceof NavigationCancel) {
    //false
  }
  if (event instanceof NavigationError) {
    //false
  }
}