0

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

2 Answers 2

1

Try this

console.log(this.user_data); //able to console the values here
this.dataTable();

Call your method hear instead of call in ngOnInit

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

Comments

0

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);
  }
 )
}

1 Comment

@Sajeetharan Congratulation for cap.. :)

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.