Im in the process of migrating an Angular v1.4 app to v5 (hopefully v6 in the new year).
The app has a number of components for example, header, tabs, grids, images, authentication etc etc.
Each component makes particular http.get
to get system and user preferences, and caches the result to avoid the app making multiple of the same http.get.
Looks like RxJS is a powerful library and have it available to use. Its seems there are many examples, methods and views of achieving this cacheing with RxJS.
Wanted to share what i have done in my v5 app and get feedback. Inspecting the app in DevTools, it seems only 1 http.get is performed, so seems like it works..
systemPreferences.service.ts:
const CACHE_SIZE = 1;
export class SystemPreferences {
private $cache: Observable<Object>
private requestConfig() {
return this.http.get("www.someurl.com").pipe(
map(response => response.value)
);
}
public getPreferences() {
if (!this.cache$) {
this.cache$ = this.requestConfig().pipe(
shareReplay(CACHE_SIZE)
);
}
return this.cache$;
}
}
header.component.ts:
ngOnInit() {
this.systemPreferences.getPreferences()
.subscribe(
(result: any) => {
this.headerTitle = result.title || '';
},
(err) => {
console.log('there has been an error');
},
() => // Some completion code
);
}
Same component code for routingGuard canActivate, tabs etc etc