簡體   English   中英

加載http數據之前Angular Not Rendering HTML

[英]Angular Not Rendering HTML before the http data is loaded

我遇到的問題是,在加載組件之前,某些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?

它不起作用的原因是,初始化組件時沒有任何數據。

您可以將其簡化為所有這些。 異步管道將負責訂閱/取消訂閱部分。 最重要的是,它將等待數據加載,然后將數據傳遞給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>

只要thedata為空,您的*ngFor將不會運行,因此該div所有內容都不會添加到DOM中。 您必須在數據加載到*ngFor外部時放置要呈現的內容。

不,您不能, *ngFor指令將元素(及其子元素)標記為“中繼器模板”,該模板會與數組中的項目數量創建重復的時間匹配。 因此,只要您輸入數組的長度為0,“中繼器模板”就不會在DOM中存在。

您可以在等待API響應時嘗試在ts中模擬帶有偽項的數組值:

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

嘗試:-

.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM