javascript - 错误类型错误 : Cannot read property '...' of undefined

标签 javascript angular typescript

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

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/

相关文章:

javascript - 如何使用javascript防止ajax响应中的window.onbeforeunload函数

旧式 JavaScript 参数中的 JavaScript ES6 花括号

javascript - 如何为新库编写 typescript 定义文件?

javascript - 无法使用node.js : io is not defined加载socket.io

node.js - Uncaught Error : Type HttpClient does not have 'ɵmod' property

angular - 将 vanilla-tilt.js 添加到 Angular 6 组件(Angular 组件中的外部 JS 库)

angular - 隐藏特定路线上的标题 - Angular 6

Angular ,在获得 promise 值后无法访问另一个函数中的值

node.js - 使用 Angular 2 observables 异步填充对象属性?

javascript - 如何使用 Javascript 在二叉搜索树中找到最长路径?