0

I am trying to make display properties in my component file html after http request. I get the properties displayed in my views but i still get an undefined error in my console. Here is my code

Here is my component.ts file

 //// component.ts
    import { AdminService } from './../../../../core/services/admin.service';
    import { Store } from '@ngrx/store';
    import { AppState } from 'src/app/core/store/state/app.state';
    import { Logout } from './../../../../core/store/actions/login/login.action';
    import { Component, OnInit } from '@angular/core';
    import { User } from 'src/app/core/models/user';

    @Component({
        selector: 'app-main-menu',
        templateUrl: './main-menu.component.html',
        styleUrls: ['./main-menu.component.scss']
     })

     export class MainMenuComponent implements OnInit {
     user: any;


    constructor(
    private adminService: AdminService,
    private store: Store<AppState>
    ) {

      this.adminService.getAuthAdmin().subscribe(
      (response: any) => {
      this.user = response.data;
     }
  );

   }

  ngOnInit() {

  }


  logout(){
    if (confirm('Are You Sure You Want To Logout?')) {
    this.store.dispatch(new Logout());
   }

 }

}

component.html file

   <div class="logged-user-info-w">
    <div class="logged-user-name">
      {{ user.full_name }}
    </div>
    <div class="logged-user-role">
      Administrator
    </div>
  </div>

The exact error I am getting is

 Cannot read property 'full_name' of undefined

Is there a workaround for this?

5
  • can you try with <div class="logged-user-name" *ngIf="user"> {{ user.full_name }} </div> Commented Dec 18, 2019 at 15:15
  • @NoahLc that actually worked. Guess I did not think about doing it that way. Was looking for a way to load it in the .ts file before displaying it in the view but this works fine Commented Dec 18, 2019 at 15:20
  • Okay I will put it Like answer Commented Dec 18, 2019 at 15:24
  • or user?.full_name Commented Dec 18, 2019 at 15:27
  • @Alexander that's even better. Thanks! Commented Dec 18, 2019 at 15:29

2 Answers 2

1

You just need to check if the user has been loaded or not. In your case, you can try with

<div class="logged-user-name" *ngIf="user"> 
    {{ user.full_name }} 
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

Just add a ? after user like this

<div class="logged-user-name" *ngIf="user"> 
  {{ user?.full_name }} 
</div>

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.