不知道为什么会发生这种情况,我从我的组件中收到此错误:
ERROR TypeError: Cannot read property 'timezone_offset' of undefined
at Object.eval [as updateRenderer] (SettingsComponent.html:16)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14377)
at checkAndUpdateView (core.js:13513)
at callViewAction (core.js:13858)
at execComponentViewsAction (core.js:13790)
at checkAndUpdateView (core.js:13514)
at callViewAction (core.js:13858)
at execEmbeddedViewsAction (core.js:13816)
at checkAndUpdateView (core.js:13509)
at callViewAction (core.js:13858)
有趣的是,它仍然在模板中显示正确的字符串,并且 ng-cli 中没有错误。以下是产生错误的组件的代码:
import { Component, OnInit } from '@angular/core';
import { GetProfileService } from '../../services/get-profile.service';
@Component({
selector: 'app-settings',
templateUrl: './settings.component.html'
})
export class SettingsComponent implements OnInit {
results: any;
profile: any;
constructor(private getProfileService: GetProfileService) { }
ngOnInit() {
this.getProfileService.profileAPI().subscribe(
data => {
this.results = data
this.profile = this.results
console.log(this.profile)
}
);
}
}
我现在只使用 {{ profile.timezone_offset }}
作为我模板上的唯一内容...
最佳答案
您的数据在渲染时似乎尚未加载到 profile
对象中。仅在异步操作完成后,才会在 profile
对象内设置数据。当您的对象在异步调用上进行操作时,应使用 ?.
。仅当定义 profile
对象时才会评估 timezone_offset
。
由于异步操作,您可能会收到该错误。尝试以下操作
{{ profile?.timezone_offset }}
关于javascript - 错误类型错误 : Cannot read property '...' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47656875/