The user can load companies by id
via a CompanyService
. As the company will not change throughout the life time of the application, I thought it would make sense to cache all already loaded items and load new ones only if needed.
Now I came up with this solution that works using an local Array<Company>
as the cache. It returns of()
of a found elment and alternativley loads a new one and stores it in the cache.
export class CompanyService {
private cache: Array<Company> = [];
private path: string = '';
getById(id: number): Observable<Company> {
const company = this.cache.find(item => item.id === id);
if (company) {
return of(company);
}
return this.http.get<any>(this.path + id).pipe(
map(response => {
this.cache.push(response);
return response;
}),
catchError(error => {
return of(null);
})
);
}
}
Is this the right way to do it?
I thought it might be better to use something like:
private cache$: Observable<Array<Company>>;
But I don't know:
- … whether this is a better approach?
- … how to add a new item?
- … how find an item in this
Observable
and return a new one otherwise?