I have an Angular 9 application that for the most part uses observables. In one component I need to:
- Get all companies (as they contain certain info I need)
- Then get all responses and map some of the extra info in the companies (i.e. the company name for the response).
- Return that list as an observabe which is subscribed to in the template using the async pipe.
To do this I originally had the following code (which appears to work):
getPopulatedResponses(): Observable<ResponseModel[]> {
return this.companyFilesStore
.select(companyFilesSelector)
.pipe(
switchMap(companies => {
return this.getAccessibleResponses(companies);
})
)
}
getAccessibleResponses(accessibleCompanies: CompanyFilesModel[]): Observable<ResponseModel[]> {
return this.responsesStore
.select(responsesSelector)
.pipe(
map((responses) => {
return responses?.map((response) => {
const company = accessibleCompanies?.find(c => c.companyGuid === response.companyId);
response.companyName = company?.companyName;
return response;
}).sort((a, b) => {
return a.completedDateTime < b.completedDateTime ? 1 : -1;
})
})
)
Firstly I'm not sure if switchMap was the right operator because if the companyFilesSelector was updating and then the responsesSelector kicked in part way through would that not terminate the previous subscription?
And now I need to also add a subscription to a filter service that I have so I've made the following changes to the getAccessibleResponses method (which again appear to be working but I feel like it may be more through luck/good connection than anything else):
getAccessibleResponses(
accessibleCompanies: CompanyFilesModel[],
): Observable<ResponseModel[]> {
return this.searchAndFilterService.getFilter()
.pipe(
switchMap(filter => {
return this.responsesStore
.select(responsesSelector)
.pipe(
map((responses) => {
return responses?.map((response) => {
const company = accessibleCompanies?.find(c => c.companyGuid === response.companyId);
response.companyName = company?.companyName;
return response;
})
?.filter(r => !r.isArchived)
?.filter(r => !filter?.selectedCompany || r.companyId === filter.selectedCompany.companyId)
?.filter(r => !filter.selectedAssessmentTemplate ||
r.assessmentTemplateId === filter.selectedAssessmentTemplate.assessmentTemplateId)
.sort((a, b) => {
return a.completedDateTime < b.completedDateTime ? 1 : -1;
})
})
)
})
)
}
I'm fairly confident this is not the best or even right approach but I'm getting a bit lost and struggling to understand how to achieve the following:
- Get all companies first and foremost.
- Combine results from the companies observable with the responses.
- When the filter is changed (i.e. the filter service observable) filter the results of 1/2.
Any help or guidance would be greatly appreciated.