Cannot read property 'title' of undefined


#1

I try to build a basic page.

In HTML

Title: {{postAbout.title}}

In TS. This works fine if object attribute is clearly defined

   private postAbout = {
     id: '',
     title: ''
   };

Use http service to load data

   ngOnInit() {
     this.getResult('postURL');
   }

   getResult(url) {
     this.mapleRestData.load(url, { id: 27 }).subscribe(
       data => { this.postAbout = data; console.log("About Page Title:" + this.postAbout.title) }
     ); 
  }

However I like to use generic object like this. It generates error

  // private postAbout = {
   //   id: '',
   //   title: ''
   //  };
   private postAbout: Object;
browser_adapter.ts:73 EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in build/pages/about/about.html:32:63
ORIGINAL EXCEPTION: TypeError: Cannot read property 'title' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'title' of undefined

I even tried to create Post Class like

  export class Post {
    id: number;
    title: String;
  }

Then define it in TS

private postAbout: Post;

It still gave me same error.


#2

You should use the safe navigation operator, i.e. change your code this way:

Title: {{postAbout?.title}}

#3

Thanks! It works as expected. Something is learned:slight_smile:


#4

It’s a small thing, and really just a matter of personal preference, but while there’s nothing wrong with @iignatov’s solution, I prefer initializing postAbout with a dummy object in the controller over using the Elvis operator in the view.

The reason for this is that I feel that the controller should be providing a contract that says “hey view, you can always rely on postAbout being a valid object (preferably with a more precise type than Object, giving more guarantees about what can be done with it)”. That way, we reduce bugs where there are many references to postAbout in the view. We no longer have to worry that each one of them is guarded against the case where postAbout is not properly defined.


#5

It is working now, can you explain why we need to use “?”. So we have to use with all of the properties ???