在从服务中检索所有数据之前,请勿加载页面

时间:2016-11-25 01:58:35

标签: angular

我试图在Angular中向浏览器显示一个简单的数据,但是我想在从服务中检索所有数据后显示数据。

怎么做?

目前,即使没有完成获取数据,页面也会显示。

以下是示例代码

In test.component.ts file

ngOnInit() {
    this._service.getQuestions().subscribe(data => { this.questionCollection = data });
}

在我的服务中

getQuestions() {
    return this._http.get('assets/questions.json')
        .map(res => res.json())
        .catch(this.handleError);
}

.html文件

<div> Other text here...... </div>
<div *ngFor="let col of questionCollection">
    <button type="button" class="btn btn-default">{{col.Text}}</button>
</div>

4 个答案:

答案 0 :(得分:5)

Angular2提供了您可以使用的AsyncPipe。正如医生所说:

  

异步管道订阅Observable或Promise并返回   它发出的最新价值。发出新值时,异步   pipe标记要检查更改的组件。当组件   被破坏,异步管道自动取消订阅以避免   潜在的内存泄漏。

阅读文档here

或 - 您可以使用旗帜。 allDataFetched。使用* ngIf:

将其与HTML绑定
<div *ngFor="let col of questionCollection" *ngIf="allDataFetched">
    <button type="button" class="btn btn-default">{{col.Text}}</button>
</div>

在组件中。您可以将此布尔变量初始化为false。加载所有数据后,您可以将其设置为true。

//component file
  allDataFetched: boolean = false;
    ngOnInit() {
        this._service.getQuestions().subscribe(data => { 
            this.questionCollection = data; 
            this.allDataFetched = true; });
    }

答案 1 :(得分:4)

Angular为此提供resolver。如果要将整个组件等到数据,则应使用resolve。如果您希望组件中的某些数据区域在数据之前不显示,请使用ngIf进行控制,如上所述。

答案 2 :(得分:3)

一种简单的方法是使用*ngIf

<ng-container *ngIf="questionCollection">
  <div> Other text here...... </div>
  <div *ngFor="let col of questionCollection">
    <button type="button" class="btn btn-default">{{col.Text}}</button>
  </div>
</ng-container>

答案 3 :(得分:1)

您可以使用异步管道,它将侦听请求observable。它预定义的角度'|异步”。