I try to group by a data in typescript from Angular to show in table
My problem is when I console log array of objects inside GroupDataForShowIntable() function It look ok but when I console log In ngOnInit() an array of objects it go outside []
import { Component, OnInit} from '@angular/core';
import { DirectiveService } from '../services/directive.service';
const groupBy = function (xs, key) {
return xs.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
@Component({
selector: 'app-my-directive',
templateUrl: './my-directive.component.html',
styleUrls: ['./my-directive.component.css']
})
export class MyDirectiveComponent implements OnInit {
constructor(private directiveService: DirectiveService) { }
dataSource = [];
displayedColumns: string[];
GroupDataForShowIntable() {
//getdata From Backend API
this.directiveService.GetMyDirectiveList().subscribe(response => {
if (response['operation'] == 'success') {
const data = response['data'];
var new_data = groupBy(data, 'directive_topic');
Object.keys(new_data).filter(key => {
this.dataSource.push({ directive_topics: key, isGroupBy: true });
let values = new_data[key];
values.filter((element) => { this.dataSource.push(element); });
});
console.log('InSideFunction', this.dataSource)
}
}, (err) => {
console.log('fail', err);
}, () => {
console.log('success');
});
}
ngOnInit(): void {
this.GroupDataForShowIntable()
console.log('OutSideFunction', this.dataSource)
this.displayedColumns = ['directive_group_name_text', 'directive_committee_position'];
}
isGroup(index, item): boolean {
return item.isGroupBy
}
}
I can't figure out why please help
I want array of objects go Inside []
CodePudding user response:
Change GroupDataForShowIntable to async function as async GroupDataForShowIntable () so that in ngInit you can use await GroupDataForShowIntable. then datasource in both function would be same. Seems more like asynchronous time issue
CodePudding user response:
The data is not outside of the array, this is just a side effect of your debugger doing lazy-loading. When you logged the array in ngOnInit
the array was empty, but by the time you've clicked the drop down in your debugger, the array was filled by the asynchronous subscribe
callback.
When you logged the data inside your function, you logged it inside the subscribe
callback, after populating the array. So of course it will already be filled when you log it.
When you click the drop-down, your debugger references the array and gets the elements. So if the array has changed since the initial log, you will see a mismatch between the first line and the actual contents.