0

I'm trying to do the binding in my angular application.

On my component.html i have:

<span>{{this.test.Username}}</span>

And this is my component.ts:

export class NavbarComponent implements AfterViewChecked, OnInit{     

   test: User;

   constructor(private userService: UserService) {                                                 
   }   

   ngOnInit() {
      var currentUser = JSON.parse(localStorage.getItem('currentUser'));
      var id = currentUser.userID;        
      this.userService.getById(id).subscribe(user => {                        
        this.test = new User();
        this.test = user;            
      });                 
   }
}

In reality, the binding works and the Username appears on the client side, but the problem is that the browser returns this error:

ERROR TypeError: Cannot read property 'Username' of undefined
at Object.eval [as updateRenderer] (NavbarComponent.html:79)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:11087)
at checkAndUpdateView (core.js:10463)
at callViewAction (core.js:10699)
at execComponentViewsAction (core.js:10641)
at checkAndUpdateView (core.js:10464)
at callViewAction (core.js:10699)
at execComponentViewsAction (core.js:10641)
at checkAndUpdateView (core.js:10464)
at callViewAction (core.js:10699)

Can someone help me?

Thanks in advance

2 Answers 2

1

set the initial value to test

test: User = { Username : null };

Or use the optional operator in the template

<span>{{this.test?.Username}}</span>
Sign up to request clarification or add additional context in comments.

Comments

0

If User is a class, initialize in constructor

 this.test = new User();

Comments

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.