2

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

Oam Psy
  • 8,555
  • 32
  • 93
  • 157
  • 2
    So what is your question? – martin Oct 23 '18 at 09:51
  • My question is that i dont know if this is the correct 'rxjs' way to perform caching? – Oam Psy Oct 23 '18 at 09:55
  • 2
    Yeah basically it is. Just be aware that you should add `take(1)` after `shareReplay` because otherwise the Observable won't complete. – martin Oct 23 '18 at 09:56
  • Possible duplicate of [What is the correct way to share the result of an Angular Http network call in RxJs 5?](https://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-http-network-call-in-r) – Buggy Oct 25 '18 at 07:52

0 Answers0