I've spent several hours trying to sort this issue out and I cannot find an answer that fits my case.
I want to display in a DataTable data composed using two API calls. Those calls are performed in a service and the data is then emitted as subject. The component subscribed to the subject then displays the data in a datatable.
The problem is that the datable doesn't show up and I have an error: TypeError: Cannot read property 'aDataSort' of undefined
. This problem didn't happen when my data source came from a single API call and I suspect my concern is that the datatable is trying to instantiate itself before the data is loaded. I can fix the issue with an *ngFor
by I have other kinds of bug, and I'd rather not do it like this.
In short, my question is: What am I doing wrong?
Here is a simplified version of my code
api.service.ts
import {Subject, Subscription} from 'rxjs';
import {HttpClient} from '@angular/common/http';
...
export class APIService implements OnDestroy {
// first data to be retrieved
private data1: data1Structure;
data1Subject = new Subject<data1Structure>();
data1Subscription: Subscription;
// second data to be retrieved
private data2: data2Structure[];
data2Subject = new Subject<data2Structure[]>();
constructor(private http: HttpClient) {}
emitData1Subject(){
this.data1Subject.next(this.data1);
}
getData1() {
this.http
.get(`${this.baseURL}data1.json`)
.subscribe(
(response) => {
this.data1Source = response;
this.emitData1Subject();
},
(error) => { console.log(error); }
);
}
emitData2Subject(){
this.data2Subject.next(this.data2.slice());
}
getData2(){
this.data1Subject.subscribe((data) => {
this.data1 = data;
this.http
.get(`${this.baseURL}data2.json`)
.subscribe(
(response) => {
// Combine the two datasets
this.data2 = this.formatData2(response);
this.emitData2Subject();
},
(error) => { console.log(error); }
);
});
}
...
}
datatable.component.ts
import {ApiService} from '../../../services/api.service';
...
export class DatatableComponent implements OnInit, OnDestroy {
data2Subscription: Subscription;
colSettings = [
{title: '#', data: 'Hid', width: '5%', visible: false},
{title: 'Date', data: 'date', width: '45%'},
{title: 'Title', data: 'title', width: '50%'}
];
dtTrigger: Subject<boolean> = new Subject();
dtOptions: DataTables.Settings;
constructor(private apiService: ApiService) {
// first API call
this.apiService.getData1();
}
ngOnInit(): void {
// second API call
this.apiService.getData2();
this.data2Subscription = this.apiService.data2Subject.subscribe(
(data2) => {
this.dtOptions = this.dataTable.getTableSettings(data2, this.colSettings);
this.dtTrigger.next();
},
(error) => { console.log(error); }
);
}
getTableSettings(records, colSettings: DataTables.ColumnSettings[]): DataTables.Settings {
return {
data: records,
columns: colSettings,
pagingType: 'full_numbers',
pageLength: 50,
deferRender: true,
dom: 'lBfrtip'
};
}
}
datatable.component.html
<table id="data2" datatable [dtOptions]="dtOptions" [dtTrigger]="dtWTrigger" class="row-border hover"></table>
Angular version: 9.1.1
Datatables version: 9.0.2
Chrome / Mac OS Catalina 10.15.5
I hope my question isn't too confusing, I really can't figure out what to do to fix this problem...
Thank you very much for your help!
Edit: fix indentation
I strongly suggest you change the way you're making your requests and merge them together in a single Observable. Seeing as you are consuming the results of your HTTP requests in your template, the best practice is to use the async
pipe with the final merged Observable:
compiledData$: Observable<CombinedDataObjectType>; // create a custom type here
ngOnInit() {
this.compiledData$ = this.http.get('firstUrl').pipe(
switchMap(firstData => this.http.get('secondUrl').pipe(
map(secondData => ({ firstData, secondData }))
)),
);
}
Your Observable now emits an Object containing both sets of data, so in the template:
<div *ngIf="compiledData$ | async as data">
<!-- Consume data here -->
</div>
Basically, avoid putting logic in subscribe
callbacks, and in fact avoid subscribing in TS wherever possible. There is almost always a more elegant, more performant, easier maintained way to do things!