首页 文章

错误TypeError:无法读取未定义的属性'…'

提问于
浏览
0

不知道为什么会发生这种情况,我从我的组件中收到此错误:

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 }} 作为我模板上唯一的东西......

2 回答

  • 1

    看来您的数据在渲染时尚未在 profile 对象中加载 . 只有在完成异步操作后才能在 profile 对象中设置数据 . 当对象在异步调用上运行时,应使用 ?. . 仅在定义 profile 对象时才会评估 timezone_offset .

    由于异步操作,您可能会收到该错误 . 请尝试以下方法

    {{ profile?.timezone_offset }}

  • 1

    使用 ?. safe navigation operator <=文档

    {{ profile?.timezone_offset }}
    

    在尝试从中访问值之前,它会检查 profile 是否存在 . 如果 profile 异步加载,这很有用 .

相关问题