Sandra Willford
Sandra Willford

Reputation: 3789

ERROR TypeError: Cannot read property '...' of undefined

Not sure why this is happening here, I am getting this error from my component:

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)

Interestingly enough it still displays the correct string in the template and there are no errors in ng-cli. Here is the code for the component producing the error:

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)
            }
        );

    }

}

I am for now just using {{ profile.timezone_offset }} as the only thing on my template...

Upvotes: 2

Views: 4747

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29775

It seems that your data has not been loaded within the profile object at the time when it was rendered. Only after the completion of asynchronous operation data is set within the profile object. ?. should be used when your object is operating on asynchronous call. timezone_offset will be evaluated only when the profile object is defined.

Due to asynchronous operation, you might be getting that error. Try the following

{{ profile?.timezone_offset }}

Upvotes: 3

Zammy
Zammy

Reputation: 573

Use the ?. safe navigation operator <= documentation

{{ profile?.timezone_offset }}

It checks if profile exists before trying to access values from it. This is usefull if profile is loaded asynchronous.

Upvotes: 2

Related Questions