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

wal*_*wal 1 angular

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

怎么做?

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

这是示例代码

In test.component.ts file

ngOnInit() {
    this._service.getQuestions().subscribe(data => { this.questionCollection = data });
}
Run Code Online (Sandbox Code Playgroud)

在我的服务中

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

.html文件

<div> Other text here...... </div>
<div *ngFor="let col of questionCollection">
    <button type="button" class="btn btn-default">{{col.Text}}</button>
</div>
Run Code Online (Sandbox Code Playgroud)

Vis*_*ati 5

Angular2提供了您可以使用的AsyncPipe.正如文件所说:

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

阅读此处的文档.

或 - 您可以使用标志.allDataFetched.使用*ngIf将其与HTML绑定:

<div *ngFor="let col of questionCollection" *ngIf="allDataFetched">
    <button type="button" class="btn btn-default">{{col.Text}}</button>
</div>
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我不认为你可以在同一个元素上使用`*ngFor`和`*ngIf`.为什么你需要一个单独的`allDataFetched`属性,当你可以查看`questionCollection`是否有一个值来知道订阅数据是否已进入? (4认同)