0

I am trying to add a dashboard component and try pass user details to it. I declare in dashboard.component.ts user: User, which has his own model and in ng on it i declared it as:

this.route.data.subscribe(data => {
      this.user = data['user'];
    });

now when i call in in html as {{user.firstName}} i get this error

ERROR TypeError: Cannot read property 'firstName' of undefined
    at Object.eval [as updateRenderer] (DashboardTopbarComponent.html:213)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:36090)
    at checkAndUpdateView (core.js:35073)
    at callViewAction (core.js:35433)
    at execComponentViewsAction (core.js:35361)
    at checkAndUpdateView (core.js:35074)
    at callViewAction (core.js:35433)
    at execComponentViewsAction (core.js:35361)
    at checkAndUpdateView (core.js:35074)
    at callViewAction (core.js:35433)

This is my dashboard.component.ts file

export class DashboardTopbarComponent implements OnInit {
  user: User;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.user = data['user'];
    });
  }
}

2 Answers 2

1

You have to remember, that js is a single threaded language. Even if you subscribed to the data and as a callback pass a function which will set your user, the user will be set only after Angular finish rendering your component, so you are trying to get field firstName, while your object is null/undefined. What you should do, is grab the user from snapshot and then subsribe to data (yes, it will be called twice but you will be handling case when user changes somehow), or wrap your template with ngIf.

Sign up to request clarification or add additional context in comments.

1 Comment

I created a resolver and add it to routes. Thanks for your help
0

You should initialize user in controller

user:User = {}

or you should check if user is exist in HTML file, try this

{{user && user.firstName}} 

2 Comments

I tried to use first option and i get this error error TS2740: Type '{}' is missing the following properties from type 'User': id, username, firstName, lastName, and 9 more.
All the props in your props interface User are required, so change = {} by = {username:"", firstName: ""} ...etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.