简体   繁体   中英

Angular2 OnInit data loading too slow causing undefined TypeError

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

I used the same code from 'heroes' example to load a detail object in a single route. I kept getting this error because, I think, the data is not loaded before the view already started to render and that's why I am getting this error.

I had this problem to display "currentUser.name" which I solved by using currentUser?.name but in this case, it doesn't make sense to add to all the places of the object properties with '?'.

I have to spend more time in OnInit than what heroes example did. Because I need to fetch more stuff. So I know that the view just kicks in much earlier than the binding object journal is loaded.

  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;
          });
        });
      });
  }

How can I instruct the view to wait until the data is loaded before it starts to render itself?

Or is there something wrong with the code?

You could wrap your template with a condition.

Steps:

1 - Create a variable and initializes it with a falsy value:

loaded: boolean = false;

2 - Set it to true when your request is finished:

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 - In your template use *ngIf to prevent errors:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM