加载http数据之前,Angular不渲染HTML

时间:2019-07-11 14:26:51

标签: angular typescript rxjs

在加载组件时,直到通过服务从api调用接收到数据之前,某些html无法加载是我的问题。

以下是相关代码:

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吗?

4 个答案:

答案 0 :(得分:1)

之所以不起作用,是因为初始化组件时没有任何数据。

您可以将其简化为所有这些。异步管道将负责订阅/取消订阅部分。最重要的是,它将等待数据加载,然后将数据传递给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>

答案 1 :(得分:0)

只要thedata为空,您的*ngFor就不会运行,因此div中的所有内容都不会添加到DOM中。在数据加载到*ngFor之外时,您将不得不放置要呈现的内容。

答案 2 :(得分:0)

不,您不能,*ngFor指令将元素(及其子元素)标记为“中继器模板”,该模板会与数组中的项目数量创建重复的时间匹配。 因此,只要您输入数组的长度为0,“中继器模板”就不会在DOM中存在。

当它等待API响应时,您可以尝试用ts中的虚拟项模拟数组值:

thedata = [1,2,3,4,5,6]

答案 3 :(得分:0)

尝试:-

.ts

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

}

.html

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