从 angular 中的数组获取空数据

getting empty data from an array in angular

我正在尝试使用数据表显示一些数据。我将数据存储在一个数组中,我可以在获取这些值后对其进行控制台操作,但是当我在数据表中对其进行控制台操作时,它会显示一个空数组。我该如何解决?

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

您需要在订阅中获取数据后调用 dataTable() 函数,否则您会在从请求接收数据之前尝试访问,改变如下,

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

试试这个

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

调用您的方法而不是调用 ngOnInit