I am new at Angular 5 + Angular Material. I was reading through the docs and trying to get a grip on the best way to load the table. I found that you could create a DataSource class and use the connect method to connect to an observable and load the table.
My task: Parse through a message and get an array of id's, then call the backend to get the corresponding object for each id. Present the list of objects in a data table.
My current solution: In my service I pass the object to getAllPatients(objet) then I get the list of object Id's, I then loop through the array and call getPatient(patient) for each object. I then subscribe to the result of getPatient, I then push the result into a list and sort the list then use a Subject.next to push out an event which contains a list of patients which is a global variable in my patientService. In my data tables DataSource class I pass the subject in the connect method.
My issue: I am not sure if there is any real unsubscribing happening, and also I am not sure if this is the cleanest approach.. as when I leave the page the calls will still continue... My biggest concern is that if you enter the page then leave and go back in quickly will it cause both batches of calls to continue and then have 2 of each object? It seems as if it doesn't happen but i am a bit worried.
Code:
Functions from my service:
getPatientDemographics(id): Observable<any> {
return this.http.get(this.userUrl + id )
}
getAllPatients(details) {
this.patients = []
var membersObj = details.getMembersObj()
if (membersObj){
for (var member of membersObj.member) {
this.getPatientDemographics(details.getMemberId(member)).subscribe(
data => {
this.patients.push(new Patient(data))
this.patients.sort(this.sortingUtil.nameCompare)
this.patientSubject.next(this.patients)
console.log(`success id ${details.getMemberId(member)}`)
},
error => {
console.log(`member id ${details.getMemberId(member)}`)
this.patientSubject.error('errr')
}
)
}
}else {
console.log(`member fail ${JSON.stringify(membersObj)}`)
}
}
Data Source class of the table:
export class PatientDataSource extends DataSource<any> {
constructor(private patientService: PatientService) {
super();
}
connect(): Subject<any[]> {
return this.patientService.patientSubject;
}
disconnect() {}
}