简体   繁体   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

I used the same code from 'heroes' example to load a detail object in a single route. 我使用了与“ heroes”示例中的代码相同的代码,以在单个路径中加载明细对象。 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 '?'. 我遇到了显示“ currentUser.name”的问题,该问题是通过使用currentUser?.name解决的,但在这种情况下,用'?'添加到对象属性的所有位置都没有意义。

I have to spend more time in OnInit than what heroes example did. 我必须在OnInit上花费比heroes榜样更多的时间。 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. 因此,我知道该视图的启动时间比绑定对象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;
          });
        });
      });
  }

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. 您可以使用条件包装template

Steps: 脚步:

1 - Create a variable and initializes it with a falsy value: 1-创建一个变量并使用falsy值对其进行初始化:

loaded: boolean = false;

2 - Set it to true when your request is finished: 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 - In your template use *ngIf to prevent errors: 3-在template使用*ngIf可以防止错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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