首页 > 解决方案 > 在加载 http 数据之前 Angular 不渲染 HTML

问题描述

我在加载组件时遇到一些 html 未加载的问题,直到通过服务从 api 调用接收到数据。

以下是相关代码:

import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  thedata;

  subscription: Subscription;

  constructor(private apiService: ApiService) {}

  ngOnInit() {
    this.getData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  getData() {
    this.apiService.getUsers().subscribe(
      (res) => {
        this.thedata = [res];
      },
      (err) => {
        console.log('There was an error: ' + err);
      }
    )
  }

}

然后在html文件中:

<div *ngFor="let data of thedata">
   <!-- other elements here and below -->
    {{ data.name }}
</div>

我的问题是,虽然有要渲染的视觉元素,但在加载数据之前它不会渲染。

有没有办法在仍然从 api 加载数据时呈现 html ?

标签: angulartypescriptrxjs

解决方案


它不起作用的原因是初始化组件时没有任何数据。

你可以把它简化成这个。异步管道将负责订阅/取消订阅部分。最重要的是,它将等待数据加载,然后将数据传递给 for 循环。

零件:

import { ApiService } from './services/api.service';

export interface ExpectedDataModel {
  name: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  myData: Observable<ExpectedDataModel[]>;

  constructor(private apiService: ApiService) {
    this.myData = this.apiService.getUsers(); // I suppose this returns an array of objects ///
  }
}

模板:

<div *ngFor="let data of myData | async">
   <!-- other elements here and below -->
    {{ data.name }}
</div>

推荐阅读