Javascript Angular2 OnInit数据加载太慢,导致未定义类型错误
我使用了来自“heroes”示例的相同代码在单个路由中加载细节对象。我一直收到这个错误,因为,我认为,数据在视图开始渲染之前没有加载,这就是我收到这个错误的原因 我在显示“currentUser.name”时遇到了这个问题,我通过使用Javascript Angular2 OnInit数据加载太慢,导致未定义类型错误,javascript,angular,Javascript,Angular,我使用了来自“heroes”示例的相同代码在单个路由中加载细节对象。我一直收到这个错误,因为,我认为,数据在视图开始渲染之前没有加载,这就是我收到这个错误的原因 我在显示“currentUser.name”时遇到了这个问题,我通过使用currentUser?.name解决了这个问题,但是在这种情况下,用“?”添加到对象属性的所有位置是没有意义的 我必须花更多的时间在OnInit上,而不是像《英雄》这样的例子。因为我需要拿更多的东西。因此,我知道视图只是在绑定对象journal加载之前启动 ERR
currentUser?.name
解决了这个问题,但是在这种情况下,用“?”添加到对象属性的所有位置是没有意义的
我必须花更多的时间在OnInit上,而不是像《英雄》这样的例子。因为我需要拿更多的东西。因此,我知道视图只是在绑定对象journal
加载之前启动
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined
如何指示视图等待数据加载后再开始渲染自身
或者代码有问题吗?您可以使用条件包装
模板
步骤:
1-创建一个变量并使用falsy
值对其进行初始化:
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;
});
});
});
}
2-当您的请求完成时,将其设置为true:
loaded: boolean = false;
3-在您的模板中
使用*ngIf
防止错误:
this.route.params
.switchMap((params: Params) => this.journalService.getJournal(+params['id']))
.subscribe((journal) => {
console.log("journal", journal);
this.journal = journal;
this.loaded = true; // -> here
});
... 内容
您可以使用条件包装模板
步骤:
1-创建一个变量并使用falsy
值对其进行初始化:
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;
});
});
});
}
2-当您的请求完成时,将其设置为true:
loaded: boolean = false;
3-在您的模板中
使用*ngIf
防止错误:
this.route.params
.switchMap((params: Params) => this.journalService.getJournal(+params['id']))
.subscribe((journal) => {
console.log("journal", journal);
this.journal = journal;
this.loaded = true; // -> here
});
... 内容
您的模板怎么样?无论如何,您可以创建一个变量,并在初始化时将其设置为false。。。当您的请求完成时,您将其设置为true。在视图中,您可以简单地使用ngIf
来检查它是否正确。这非常有效,谢谢@developer033您应该提供注释作为答案,以便OP可以接受it@echonax完成:)您的模板如何?无论如何,您可以创建一个变量,并在初始化时将其设置为false。。。当您的请求完成时,您将其设置为true。在视图中,您可以简单地使用ngIf
来检查它是否正确。这非常有效,谢谢@developer033您应该提供注释作为答案,以便OP可以接受it@echonax完成了:)