从角度数组中获取空​​数据

时间:2018-12-12 18:03:44

标签: angular datatables angular-datatables

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

  

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 个答案:

答案 0 :(得分:1)

在订阅中获取数据后,您需要调用 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);
  }
 )
}

答案 1 :(得分:-1)

尝试

<div class="parent-container">
    <div>
        <div>
            <h3>header 1</h3>
            <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
        <div class="img-container">
            <img src="https://place-hold.it/300x500">
        </div>
    </div>

    <div>
        <div>
            <h3>header 2</h3>
            <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor
                sit amet.</p>
        </div>
        <div class="img-container">
            <img src="https://place-hold.it/300x500">
        </div>
    </div>

    <div>
        <div>
            <h3>header 3</h3>
            <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor
                sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
        </div>
        <div class="img-container">
            <img src="https://place-hold.it/300x500">
        </div>
    </div>
</div>

调用您的方法,而不是调用console.log(this.user_data); //able to console the values here this.dataTable();