I want to get a list from chrome storage and show it in my angular component, currently I'm using the function like this
myList: any[];
dataSource: MatTableDataSource<any>;
@ViewChild(MatTable, {static: true}) table: MatTable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private fb: FormBuilder,
private globalsService: GlobalsService,
private snackbar: MatSnackBar) {
chrome.storage.sync.get(['mylist'], this.getLists);
}
getLists(value: any): any{
this.myList = value.mylist;
this.dataSource = new MatTableDataSource<any>(this.myList);
}
The issue is that I'm getting this error: TypeError: Cannot read property 'length' of undefined
, in my html file for that component I use the property length for myList to use mat-paginator
like this:
<mat-paginator #paginator [length]="myList.length" [pageSize]="5" [pageSizeOptions]="[5, 10, 20]"></mat-paginator>
Apparently myList is always returning undefined, but it's not returning undefined when I do a console.log(value.mylist)
inside the getLists
function, how could I fix this?
I solved it using Promises
:
myList: any[] = [];
@ViewChild(MatTable, {static: true}) table: MatTable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private fb: FormBuilder,
private globalsService: GlobalsService,
private snackbar: MatSnackBar) {
getLists().then((value) => {
this.myList = value.myList;
this.dataSource = new MatTableDataSource<any>(this.myList);
});
}
getLists = (): any => {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(['myList'], (value) => {
if (value !== undefined){
resolve(value);
}
else {
reject();
}
});
});
};