簡體   English   中英

Angular2 OnInit數據加載太慢導致未定義的TypeError

[英]Angular2 OnInit data loading too slow causing undefined TypeError

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined

我使用了與“ heroes”示例中的代碼相同的代碼,以在單個路徑中加載明細對象。 我一直收到此錯誤,是因為我認為在視圖開始渲染之前未加載數據,這就是為什么我收到此錯誤。

我遇到了顯示“ currentUser.name”的問題,該問題是通過使用currentUser?.name解決的,但在這種情況下,用'?'添加到對象屬性的所有位置都沒有意義。

我必須在OnInit上花費比heroes榜樣更多的時間。 因為我需要獲取更多東西。 因此,我知道該視圖的啟動時間比綁定對象journal的加載要早得多。

  ngOnInit() {
    this.userService.getUser().then( (user) => {
      this.currentUser = user;
      this.accountsService.getAccounts().then( (accounts) => {
        this.accounts = accounts;
        this.userAccounts = this.currentUser.accounts.map(
          accountId => this.accounts.find(
            elem => elem.id == new String(accountId)
          )
        );
        this.route.params
          .switchMap((params: Params) => this.journalService.getJournal(+params['id']))
          .subscribe( (journal) => {
            console.log("journal", journal);
            this.journal = journal;
          });
        });
      });
  }

我如何指示視圖等待數據加載后才開始呈現自身?

還是代碼有問題?

您可以使用條件包裝template

腳步:

1-創建一個變量並使用falsy值對其進行初始化:

loaded: boolean = false;

2-完成請求后,將其設置為true:

this.route.params
.switchMap((params: Params) => this.journalService.getJournal(+params['id']))
.subscribe((journal) => {
  console.log("journal", journal);
  this.journal = journal;
  this.loaded = true; // -> here
});

3-在template使用*ngIf可以防止錯誤:

<ng-container *ngIf="loaded">
  ... content
</ng-container>

暫無
暫無

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

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