【问题标题】:getting empty data from an array in angular从角度数组中获取空​​数据
【发布时间】:2018-12-12 18:03:43
【问题描述】:

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

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

【问题讨论】:

    标签: angular datatables angular-datatables


    【解决方案1】:

    试试这个

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

    调用你的方法,而不是调用ngOnInit

    【讨论】:

      【解决方案2】:

      获取订阅中的数据后,需要调用dataTable()函数,否则在从请求中收到数据之前尝试访问,修改如下, p>

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

      【讨论】:

      • @Sajeetharan 恭喜获得上限.. :)
      猜你喜欢
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2016-07-28
      • 2018-11-06
      相关资源
      最近更新 更多