Search code examples
angulardatatablesangular-datatables

getting empty data from an array in angular


I'm trying to display some data using datatable. I have data stored in an array and I'm able to console those values after fetching them but when i console it in the datatable it shows an empty array. How do I resolve this?

component.ts

user_data:any= [];

constructor(private http:Http, private Authentication:AuthService) {}

getUsersFromServices():void{
this.Authentication.fetch_userdata().subscribe(
  (data) =>{ 
    this.user_data = data;  
    console.log(this.user_data); //able to console the values here
  },err =>{
    console.log(err);
  }
 )
}

dataTable(){
console.log(this.user_data); //getting an empty array here
this.dtOptions = {
  pagingType: 'full_numbers',
  pageLength: 4,
  columnDefs:[{
    targets:[0,1,2,3,4],
    orderable:false
  }],
  data:this.user_data,
  columns:[
    {
      title:'id',
      data:'user.id'
    },
    {
      title:'First Name',
      data:'user.first_name'
    },
    {
      title:'Last Name',
      data:'user.last_name'
    },
    {
      title:'Email',
      data:'user.email'
    },
    {
      title:'Role',
      data:'role'
    }
  ]
};
}


ngOnInit(): void {
this.getUsersFromServices();
this.dataTable();
}

data after fetching

data while consoling in the datatable


Solution

  • You need to call the dataTable() function once you get the data within your subscribe, otherwise you are trying to access before the data being recieved from the request, change it as follows,

    this.Authentication.fetch_userdata().subscribe(
      (data) =>{ 
        this.user_data = data;  
        console.log(this.user_data); //able to console the values here
        this.dataTable();
      },err =>{
        console.log(err);
      }
     )
    }